I have multiple commands but none of thme seem to work, I had all of them in an on_message event, which I thought to be the prolem so I moved it all into seperate commands. There are no errors.
import discord
from googleapiclient.discovery import build
from discord.ext import commands
from PIL import Image, ImageFont, ImageDraw
import requests
import json
import textwrap
import random
yt_api_key = ''
youtube = build("youtube", 'v3', developerKey=yt_api_key)
description = '''blank'''
intents = discord.Intents.default()
client = discord.Client()
bot = commands.Bot(command_prefix='$', description=description, intents=intents)
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#bot.command()
async def test(ctx):
await ctx.send('test')
Thanks in advance!
I found the problem! I'm going to leave this here for anyone else with the same problem.
All I did was remove the bot variable and made it into the client one.
I think that the two were overlapping eachother.
import discord
from googleapiclient.discovery import build
from discord.ext import commands
from PIL import Image, ImageFont, ImageDraw
import requests
import json
import textwrap
import random
yt_api_key = ''
youtube = build("youtube", 'v3', developerKey=yt_api_key)
description = '''blank'''
intents = discord.Intents.default()
#-----------changed this---------------
client = commands.Bot(command_prefix='$')
#--------------------------------------
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
#-------------and this----------------
#client.command()
#--------------------------------------
async def test(ctx):
await ctx.send('test')
Related
# bot.py
import discord
import os
import random
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = "token"
intents = discord.Intents.all()
intents.message_content = True
bot = commands.Bot(command_prefix='.', intents=intents)
#bot.event
async def on_ready():
print(f'{bot.user.name} text')
#bot.command(name='rastgelefilm')
async def rf(ctx):
with open("movies.txt") as f:
lines = f.readlines()
response = random.choice(lines)
await ctx.send(response)
bot.run(TOKEN)
I'm making a Discord bot and I'm trying to run this code but send doesn't work and it's white on Visual Studio Code. Is something wrong with the code?
I tried these two.
async def fn(ctx:discord.ApplicationContext):
ctx.channel.send()
Problem : nextcord.ext.commands.errors.CommandNotFound: Command
"roles" is not found
cog.py file:
from nextcord.ext import commands
from button_roles.role_view import RoleView
class ButtonRoles(commands.Cog, name="Board Roles"):
def __init__(self, bot: commands.Bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
self.bot.add_view(RoleView())
#commands.command()
#commands.is_owner()
async def roles(self, ctx: commands.Context):
await ctx.send("Click a button to add or remove a role.", view=RoleView())
def setup(bot: commands.Bot):
bot.add_cog(ButtonRoles(bot))
role_view.py file:
import nextcord
from bot import custom_id
import config
VIEW_NAME = "RoleView"
class RoleView(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
#nextcord.ui.button(label="NSFW", emoji=":dart:", style=nextcord.ButtonStyle.primary, custom_id=custom_id(VIEW_NAME, config.NSFW_ROLE_ID))
async def nsfw_button(self, button, interaction):
interaction.response.send_message("Ты получил NSFW роль")
bot.py file
from code import interact
from unicodedata import name
from nextcord.ext import commands
import config
import os
import nextcord
import textwrap
import requests, json, random, datetime, asyncio
from PIL import Image, ImageFont, ImageDraw
from nextcord import File, ButtonStyle, Interaction, ChannelType, SlashOption
from nextcord.ui import Button, View
from nextcord.abc import GuildChannel
from dotenv import load_dotenv
load_dotenv()
intents = nextcord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=config.PREFIX, intents=intents)
serverID = config.GUILD_ID
BOT_NAME = config.BOT_NAME
#bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
#bot.slash_command(name="add", guild_ids = [serverID])
async def add(ctx, left: int, right: int):
"""Слаживать левое и правое число"""
await ctx.send(left + right)
#bot.slash_command(name="splx", guild_ids = [serverID])
async def _bot(ctx):
"""Вся инфа"""
await ctx.send("Читается как Суплекс а не спликс")
def custom_id(view: str, id: int) -> str:
return f"{config.BOT_NAME}:{view}:{id}"
if __name__ == '__main__':
bot.run(os.getenv("DISCORD_TOKEN"))
Bot successfully running without problems, and others commands running also without mistakes, however instead of $roles one
I need to know how to make a bot able to react to a trigger $roles, thanks (i'm new in discord bots developing so sorry bcs of my stupism)
well, the commands was indented incorrectly in the cog file.
you should make the commands defined in the cog file in the cog defination, like this:
class ABC(commands.Cog):
...
# like this, the commands defination should be cog defination indent level+1
#commands.command()
...
# NOT like this
#commands.command()
...
I'm currently developing a discord bot that grabs the user IP, with their permission.
For that I would like that once they clicked on the link I'd display on the embed that the bot has given them the verified role.
I'm facing some issues with this.
My code:
import discord
from discord.ext import commands
import requests
from requests import get
from bs4 import BeautifulSoup
import os
import socket
import asyncio
bot = commands.Bot(command_prefix = "!", case_insensitive = True)
BOT_TOKEN = "my_token"
#bot.event
async def on_ready():
print('Connected to bot: {}'.format(bot.user.name))
print('Bot ID: {}'.format(bot.user.id))
print('''
██████╗░░░█████╗░████████╗███████╗░
██╔══██╗░██╔══██╗╚══██╔══╝██╔════╝░
██████╦╝░██║░░██║░░░██║░░░█████╗░░░
██╔══██╗░██║░░██║░░░██║░░░██╔══╝░░░
██████╦╝░╚█████╔╝░░░██║░░░███████╗░
╚═════╝░░░╚════╝░░░░╚═╝░░░╚══════╝░
''')
print('\nConnected to bot: {}'.format(bot.user.name))
print('Bot ID: {}'.format(bot.user.id))
await bot.change_presence(activity=discord.Game(name="Grabbing your stuff"))
#bot.command()
async def verify(ctx):
nome=ctx.author.name
embed = discord.Embed(
title=nome,
description = ':flag_pt:Clica [aqui]("site") para te verificares\n :flag_us:Click [here]("site") to verify',
colour = discord.Colour.green()
)
botmsg = await ctx.send(embed = embed)
await botmsg.add_reaction("✅")
bot.run(BOT_TOKEN)
I run this, it connects however when running it will not return anything when it comes to commands. I've tried changing this to the context return method from on every message. Previously only one message would appear, now none with this method even though both commands are the same with slight differences. What is my error on this? Sorry this is literally my first attempt at a discord bot.
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
discClient = discord.Client()
bot = commands.Bot(command_prefix = "!")
#discClient.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
discClient.run(botToken)
You heading in the right direction commands.Bot have both event and command no need to use a client just for events.
You should either use discord.Client or commands.Bot not both in your case it is commands.Bot.
Also you are running the client only
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
botToken = os.getenv("DiscBotToken")
bot = commands.Bot(command_prefix = "!")
#bot.event
async def on_ready():
print(f"{discClient.user} is now connected.")
print('Servers connected to:')
for guild in discClient.guilds:
print(guild.name)
#bot.command(name = "about")
async def aboutMSG(ctx):
aboutResp = "msg"
await ctx.send(aboutResp)
#bot.command(name = "test")
async def testMSG(ctx):
testResp = "msg"
await ctx.send(testResp)
bot.run(botToken)
I am currently trying to create my discord bot. sadly, this does not work and I have no Idea why...
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))
there are NO errors. But no output aswell. I try making it join my vc by writing: .join
channel returns None, because ctx.message.author don't have voice attribute. Also, Client.join_voice_channel is deprecated since v1.0 (read here)
Instead of that, try this:
import discord
import os
import time
from ka import keep_alive
from discord.ext import commands
import asyncio
client = commands.Bot(command_prefix = '.')
prefix = '.'
#client.event
async def on_ready():
print("I'm ready! {0.user}".format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Croissants!"))
#client.command()
async def join(ctx):
channel = ctx.guild.get_member(ctx.author.id).voice.channel # This
await channel.connect()
await ctx.send("On my way!")
client.run(os.getenv('TOKEN'))
Do client.add_command(join). You currently have the function for your command, but you haven't told the bot to recognize it as a command.