Discord Bot Command_not_work - python

My console dont show any errors, the slash commands works, but when I type "!dog", it should return "dog", but nothing happen.
'''
import discord
import random
from discord import app_commands
from discord.ext import commands
id_do_servidor = my_server_id
class client(discord.Client):
bot = commands.Bot(command_prefix='!',intents=discord.Intents.all())
def __init__(self):
super().__init__(intents=discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(
guild=discord.Object(id=id_do_servidor)
)
self.synced = True
print(f"{self.user.name} is online.")
aclient = client()
tree = app_commands.CommandTree(aclient)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
#bot.command(name='dog')
async def sapo(ctx):
await ctx.send('dog')
#tree.command(guild=discord.Object(id=id_do_servidor),
name='test',
description='test')
async def slash2(interaction: discord.Interaction):
await interaction.response.send_message(f"Working!",
ephemeral=True)
aclient.run(
'my_bot_token')
'''
If someone know a solution, please help me, thanks for your atention.

You have both a discord client (aclient), and the bot object (bot), in your code, but you only run the bot on aclient (and the commands are registered to the bot object, so hence do not work). You cannot use both a client and bot object at the same time. In your instance, change class client(discord.Client): to class client(commands.Bot): and change the constructor to have the parameters you've used with the bot: super().__init__((command_prefix="!", intents=discord.Intents.default())
Then, simply replace any more references in your code using bot to aclient, ie:
#bot.command(name='dog') -> #aclient.command(name='dog')

Related

Discord.py Commands Unresponsive

I am trying to make a bot with a simple function of creating a channel, but it is unsuccessful.
Here's my code:
import os
import discord
from keep_alive import keep_alive
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='$',intents=intents)
guild = discord.Guild
#client.event
async def on_ready():
print("I'm in as " + str(client.user))
#bot.command(name = "hack")
async def court_create(ctx, msg):
print("Received: $hack") #output to console
channel_name = "hack-" + str(msg)
await ctx.send(channel_name) #output to channel
channel = await guild.create_text_channel(name = channel_name)
keep_alive()
Token = os.environ['Token']
client.run(Token)
Note that for debugging, I added two lines so that when it receives the command, it prints out to both the console and the channel. However, when I typed $hack 123 into the channel, it did nothing, not even outputting Received: $hack. Any ideas about this?
Bot has manage channel permission.
#bot.command(name = "hack")
async def court_create(ctx, msg):
The name in bot.command and the name of the function are two completely different names. It only reads what the function name is. If you want to add hack as another method of using the command you can use the aliases argument in bot.command()
Example:
#bot.command(aliases=["hack"])
async def court_create(ctx, msg):

Runtime error not showing when using asyncio to run discord bot

I'm developing discord bot with discord.py==2.1.0.
I use cog to write the main function that I wanna use, but I found when the whole bot is wrapped in async function and called by asyncio.run(), my terminal won't show any error message when there is any runtime error in my cog script.
Here is the example application. I stored my bot token in environment variable.
bot.py
import os
import discord
from discord.ext import commands
import asyncio
token = os.environ["BOT_TOKEN"]
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
description = "bot example."
super().__init__(
command_prefix=commands.when_mentioned_or('!'),
intents=intents,
description=description
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
bot = Bot()
async def load_extensions():
for f in os.listdir("./cogs"):
if f.endswith(".py"):
await bot.load_extension("cogs." + f[:-3])
async def main():
async with bot:
await load_extensions()
await bot.start(token)
asyncio.run(main())
./cogs/my_cog.py
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print("Ready")
#commands.command()
async def command(self, ctx):
test_error_message() # An runtime error example
print("Command")
async def setup(client):
await client.add_cog(Test(client))
Command that I run in terminal to start the bot.
python bot.py
When I type !command in the discord channel, there is no error message showing in the terminal, but there is no "Command" printed out so I'm sure the code stopped at the line I called test_error_message()
I expected that it should show error message normally, but I cannot find useful reference to make it work :(
There is one reason I need to use asyncio, I have a task loop to run in the bot, like the code below.
from discord.ext import tasks
#tasks.loop(seconds=10)
async def avatar_update():
# code here
async def main():
async with bot:
avatar_update.start()
await load_extensions()
await bot.start(token)
I would happy to know if there are some great practice to handle error in this situation.
Thanks!
Client.start() doesn't configure logging, so if you want to use that then you have to do it yourself (there's setup_logging to add a basic config). run() configures logging for you.
For more info, read the docs. https://discordpy.readthedocs.io/en/stable/logging.html?highlight=logging

Discord.py - Can't get custom commands to work within inherited class

I'm trying to get custom commands to work in my Discord server. But it doesn't work when I'm not using a decorator, and I do not know how to make it work within a class.
Please help.
(XXX.. just replaces an ID here)
Please have a look at add_my_commands() function. This one should be able to take the prefix and respond with the info. This doesn't work currently.
I have a main.py file which runs separately, as follows:
# Import discord.py
import discord
from discord.ext import commands
# Import Bot Token
from apikeys import *
# Import classes
from steward_bot import MyClient
intents = discord.Intents.default() # or .all() if you ticked all, that is easier
intents.message_content = True
intents.members = True # If you ticked the SERVER MEMBERS INTENT
# Initialize client
bot = MyClient(command_prefix="!", intents=intents)
bot.run(DISCORD_TOKEN)
The MyClient class:
class MyClient(commands.Bot):
def __init__(self, *args, command_prefix, **kwargs):
super().__init__(
*args, command_prefix=command_prefix, case_insensitive=True, **kwargs
)
self.target_message_id = XXXX
self.add_my_commands()
async def on_ready(self):
print("We have logged in as {0.user}".format(self))
print("---------------------------------------------")
async def on_member_remove(self, member):
channel = self.get_channel(XXXX)
await channel.send("Goodbye")
async def on_raw_reaction_add(self, payload):
"""
Give a role based on a reaction emoji
"""
if payload.message_id != self.target_message_id:
return
guild = self.client.get_guild(payload.guild_id)
print(payload.emoji.name)
print("Hello")
# Responding to messages
async def on_message(self, message):
if message.author == self.user:
return
if message.content == "Test":
await message.channel.send("Hey hey chill")
if message.content == "cool":
await message.add_reaction("\U0001F60E")
if message.content == "give me our prefix":
await message.channel.send(str(self.command_prefix))
await self.process_commands(message)
# Throws out reactions to messages
async def on_reaction_add(self, reaction, user):
await reaction.message.channel.send(f"{user} reacted with {reaction.emoji}")
def add_my_commands(self):
#self.command(name="info", pass_context=True)
async def info(ctx):
"""
ctx - context (information about how the command was executed)
info
"""
print(ctx)
await ctx.send("Hello X")
await ctx.send(ctx.guild)
await ctx.send(ctx.author)
await ctx.send(ctx.message.id)
Within the server, I want to run the command "!info" and get the information out. Would appreciate any help!
No need to define your entire bot within a class. Create a main.py file with your bot defined and import cogs from there. I'd also set up my commands through a cog with commands.command().
Example of how I'd go about adding an !info command:
main.py
import discord
from discord.ext import commands
from info import InfoCog
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
intents.messages = True
intents.reactions = True
intents.presences = True
# Initialize client
bot = commands.Bot(command_prefix='!', intents=intents)
bot.add_cog(InfoCog(bot))
#bot.event
async def on_ready(self):
print("We have logged in as {0.user}".format(self))
print("---------------------------------------------")
bot.run(TOKEN)
info.py
import discord
from discord.ext import commands
class InfoCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.command()
async def info(self, ctx):
await ctx.send('Info')
Or, you could jumble everything into one file. This is how I used to do it with all my commands & events. It was easier to get the hang of at first.
main.py
# Import discord.py
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
intents.messages = True
intents.reactions = True
intents.presences = True
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.event
async def on_ready(bot):
print("We have logged in as {0.user}".format(bot))
print("---------------------------------------------")
# [...]
#bot.command()
async def info(ctx):
await ctx.send('info')
# [...]
#bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content == "give me our prefix":
await message.channel.send(str(bot.command_prefix))
if message.content == "Test":
await message.channel.send("Hey hey chill")
# [...]
#bot.event()
async def on_member_remove(member):
channel = bot.get_channel(CHANNELID)
await channel.send(f"Goodbye, {member}")
# [...]
bot.run(TOKEN)

Implement guild command testing in cog slash commands

I am trying to learn discord.py V2.0. If I create a slash command without entering a guild to use then I takes some time before discord updated the bot slash command list. The qustion is how should I provide the guilds in my cog python file?
Here is my main.py:
import os
import asyncio
#---
import discord
from discord import app_commands
from discord.ext import commands
#---
MY_GUILD = discord.Object(id=1041079018713260173)
TOKEN = "token goes here"
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
class abot(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.bot = bot
self.synced = False
self.tree = app_commands.CommandTree(self.bot)
async def on_ready(self):
await self.tree.sync(guild=MY_GUILD)
self.synced = True
async def load():
print("---Cogs---")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")
print(f'[i]: Loaded "{filename}" into cogs')
async def main():
await load()
await bot.start(TOKEN)
asyncio.run(main())
Here is the event.py file inside of "cogs" folder:
import asyncio
import os
#---
import discord
from discord import app_commands
from discord.ext import commands
status = "testar bara..."
MY_GUILD = discord.Object(id=1041079018713260173)
class events(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print("---Info---")
print(f'Logged in as | "{self.bot.user}" | and is now online!')
await self.bot.change_presence(status=discord.Status.online, activity=discord.Game(status))
print(f'Updated status to -> "{status}"')
print("Running and listening for commands....")
print(f"----")
#app_commands.command(name = "latency", description="brrarar testar")
async def latencyf(self, interaction: discord.Interaction):
await interaction.response.send_message(f"test... test...")
async def setup(bot):
await bot.add_cog(events(bot))
You do not need to provide the guilds yourself. You can use bot.guilds, which provides a list of all the guilds where the bot is connected to.

userlist of a specific role in the discord (Python)

I would like to have a command to get a list of ALL users with a special role.
But this doesn't really work.
Everything is output, but not the members.
Does anyone here have an idea what this is about? Or even a better alternative?
Many thanks in advance
import discord
import asyncio
from discord import message
from discord.ext import commands
intents = discord.Intents.all()
client = discord.Client(intents=intents)
class ClansCog(commands.Cog, name='Clans'):
def __init__(self, bot):
self.bot = bot
#commands.command(pass_context=True)
async def deutsch(self, ctx, *args):
if ctx.channel.type is not discord.ChannelType.private:
await ctx.message.delete()
roll_id = 733988944--------
guild_id = 71911198261------
guild = self.bot.get_guild(guild_id)
partner_role = guild.get_role(roll_id)
print(partner_role.members)
print(partner_role.id)
print(client.guilds)
def setup(bot):
bot.add_cog(ClansCog(bot))
print('Clans loaded!')
From Terminal
[]
733988944533-------
[]
A friend and I found the problem.
It was an intents problem (thanks Shnap :) )
bot = commands.Bot(command_prefix='d!'.lower(), case_insensitive=True, intents=intents)
intents=intents was missing, after that no more problem

Categories