#discord-bots
1 messages · Page 380 of 1
There's not a single question mark in that post
@wild gate what is your question lol
@wild gate You did not ask a single question but i guess you need something like that
from aiohttp import web, web_request, ClientSession
from discord.ext import commands
import json
import subprocess
class WebServer(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.api_url = 'http://localhost:5000'
@commands.command()
async def execute(self, ctx: commands.Context, *, command):
async with ClientSession() as session:
url = self.api_url + '/execute'
data = {'command': command}
async with session.post(url, data=json.dump(data)) as response:
if response.status_code == 200:
await ctx.channel.send(f'Command executed: {command}')
else:
await ctx.channel.send(f'Failed to execute command: {command}')
async def execute_command(self, request: web_request.Request):
data = await request.json()
command = data.get(command)
try:
result = subprocess.checkoutput(command,
stderr=subprocess.STDOUT,
shell=True,
text=True)
return web.Response(
status=200,
text=json.dumps({"result": result}),
content_type='application/json')
except subprocess.CalledProcessError as e:
return web.Response(
status=400,
text=json.dumps({"error": str(e.output)}),
content_type='application/json')
async def cog_load(self):
app = web.Application()
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host='0.0.0.0', port=5000)
await site.start()
app.router._frozen = False
app.router.add_post('/execute', self.execute_command)
app.router.freeze()
async def setup(bot):
await bot.add_cog(WebServer(bot))
well I get a bit better understanding now what I need to do, it's like if I host a server on like a digital ocean VM what would it look like not in terms of code but more like what do I need to do if I want to have the application waiting for commands from the discord bot
like the code I can always figure out
it's more the idea of what am I doing I need a better understanding of
What you asked was fairly general. What are users doing, what are the "commands" you're looking to run? What is the overall purpose?
It's to connect to a game, I mean it's just basic like / commands in the discord server, and for the commands they're just functions that'll do stuff in game I already have built I just need like info on what I need to do in terms of hosting like do I need a server or can I just run it all on a VM that is hosted by digital ocean and like just have my discord bot connect to the VM, like i have no idea what I need to do in terms of hosting basically
idk I'm wathcing a few yt videos rn on discord bots my questions will prolly be clearer in a bit I'm just gonna ask tmrw
Anywhere you could run a python program, you could run a discord bot. Just needs network access to discord and a few libraries
Any other requirements are entirely what you're doing inside of that bot, i.e. running other stuff, connecting to other systems, etc etc
why other member can also search for this command if i have locked this command to myself?
RuntimeError: Numpy is not available
pip install numpy
i did
how many python version are available?
how i check
py --version
3.11.9
the everyone role needs to be denied to hide your command from anyone that doesnt have the manage server permission
ok what is channel over ride thing
do pip show numpy
then what
see its installed or not
it is
have u tried the command?
yes
btw by any chance r u working in virtual env?
no
i recommend u to do that then u wont have these kind of issue
i personally use poetry to manage the virual env and dependencies
that just lets you (dis)allow the command for specific channels
do yk how to fix AttributeError: module 'discord' has no attribute 'Bot'
its a error w my other bot
?
i need to check your script
dms
please refrain from using that 😅 asking here will benefit even more user with same issue
saves effort and time
oh i didnt known u can send code in here
says this now
hmm do like this
class MyBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
bot = MyBot(intents=intents)
define it
then you should learn the basics first
even if i tell u , u wont be able to make changes if u dont understand what the error is trying to say
can u still tell me
this will be last chance i am spoonfeeding u after this time please complete your basics first
intents = discord.Intents.all()
this will enable all intents
i wont tell answer of this u need to figure it out , its clearing stating whats the issue , please refer to the docs
bro, im just trying to get help dude
!d discord.ext.commands.Bot.command_prefix
The command prefix is what the message content must contain initially to have a command invoked. This prefix could either be a string to indicate what the prefix should be, or a callable that takes in the bot as its first parameter and discord.Message as its second parameter and returns the prefix. This is to facilitate “dynamic” command prefixes. This callable can be either a regular function or a coroutine.
An empty string as the prefix always matches, enabling prefix-less command invocation. While this may be useful in DMs it should be avoided in servers, as it’s likely to cause performance issues and unintended command invocations.
i am also trying to help you by giving you resources where to find answer so u can learn
im not a dev, im js tryna run this bot for my friend
copying pasting wont help , you might want to add commands right? if u dont learn then u wont be able to add commands and make changes
i dont wanna add cmds
then googling can help
chatgpt
!rule 10
yep
but idk how to put it into the MyBot
btw u need to use mybot
ok
u made subclass of commands.Bot with mybot so u need to use that
ok
can u send it
or help me fix TypeError: BotBase.init() missing 1 required positional argument: 'command_prefix'
dude just read the error once and see what u did above
check this out
whats the error?
RuntimeError: Numpy is not available
your error says numpy is not installed
no cus i did pip install numpy
maybe its a py version issue
Python 3.11.9
Requirement already satisfied:
above u said u r using 3.9 something and now py 3.11.9 r u sure u r not using two version of py?
ye cus i tried to use 3.2 to see if it fixed but it didnt so i went back to 3.1 and uninstalled 3.12
try pip install -m numpy
see it solves or not
no such option: -m
python -m pip install numpy
Requirement already satisfied
yes

i dont have idea what to do if your current py has numpy installed and its not showing it and u r claiming only 1 py version u have
is there any event which tells who deleted the message if its the author himself?
no
in discordpy, whats the difference between on_error and on_command_error
!d discord.discord.ext.commands.on_command_error
discord.ext.commands.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.
A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.on_command_error)).
!d discord.app_commands.CommandTree.on_error
await on_error(interaction, error, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when any command raises an [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError).
The default implementation logs the exception using the library logger if the command does not have any error handlers attached to it.
To get the command that failed, [`discord.Interaction.command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.command) should be used.
@brazen crane
thanks
yw
is on_application_command_error a thing?
Is that a thing in d.py?
idrk
hhhmmm yea i dont think so
That exists in pycord https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.on_application_command_error
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, default_command_contexts, default_command_integration_types,...
A pretty useful error handler for slash commands idk what's it called in dpy if it exists
^that in d.py
O
on_raw_member_remove and on_member_remove whats the difference like raw one can be called ? like if bot isnt online it wont post then in what scenario raw on will be useful?
Everything is mentioned in the docs
# News Command Group
@commands.group(name="news", invoke_without_command=True)
async def news(ctx):
if ctx.invoked_subcommand is None:
await ctx.send('Invalid news command.')
# Subcommands for news command
@news.command(name='setreviewchannel', description="Set review channel for news articles.")
async def news_setreviewchannel(ctx, channel: discord.TextChannel):
try:
with open('main.json', 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = {}
data['review_channel_id'] = channel.id
with open('main.json', 'w') as f:
json.dump(data, f, indent=4)
await ctx.send(f'Review channel set to {channel.mention}')``` i did the command group in attempt to have spaces in the commands not dashes but theres still dashes
@turbid condor you available for this one
like i wanted it to show as /news setreviewchannel
but its /news-setreviewchannel
This appears to be a prefix command group rather than slash
how can i fix
What fix make it a app_command group or hybrid_group
@app_commands.Group(name='news', description="News related commands.")
async def news(ctx):
if ctx.invoked_subcommand is None:
await ctx.send('Invalid news command.')```
like this right? and the what should i do for the subcommands decorator
use news
from discord.app_commands import Group, command
from discord.ext.commands import GroupCog
# option 1 - this can be used inside a cog
my_group = Group(name='group', description='description')
@my_group.command()
async def subcommand(interaction: Interaction):
...
subgroup = Group(parent=my_group, name='subgroup', description='description')
@subgroup.command()
async def subsubcommand(interaction: Interaction):
...
tree.add_command(my_group)
# option 2 - this cannot be used inside a cog
class MyGroup(Group, name='group', description='description'):
@command()
async def subcommand(self, interaction: Interaction):
...
subgroup = Group(name='subgroup', description='description')
@subgroup.command()
async def subsubcommand(self, interaction: Interaction):
...
tree.add_command(MyGroup())
# option 3 - this IS a cog
class MyGroup(GroupCog, group_name='group', group_description='description'):
@command()
async def subcommand(self, interaction: Interaction):
...
subgroup = Group(name='subgroup', description='description')
@subgroup.command()
async def subsubcommand(self, interaction: Interaction):
...
await bot.add_cog(MyGroup()) # this is the only time guild(s) kwarg is valid in add_cog
```Note: Groups can only be nested once. <https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups>
These are 3 different methods
@news.command(name="news-setreviewchannel", description="Set review channel for news articles.")
async def new_setreviewchannel(interaction: discord.Interaction, channel: discord.TextChannel):
try:
with open('main.json', 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = {}
data['review_channel_id'] = channel.id
with open('main.json', 'w') as f:
json.dump(data, f, indent=4)
await interaction.response.send_message(f'Review channel set to {channel.mention}')``` did i do something wrong all of my commands dissapeared
How is Group defined, and how is this being added to your bot?
i already checked the docs i didnt understood it
if bot is turned on and then something happens means it will be cached then whats the point of raw this is what i am trying to understand
The on_member_remove wont be executed when the bot is in it's startup stage where the interal cache isnt fully ready and youll have to catch it in the on_raw_member_remove
although for this specefic event the chances of the member not being in the cache in a normal state is really low
but if your bot is present in a lot of servers (probably 5k+ i think?), the chances of the member not being cached will be common i guess
# BAN CMD
@commands.has_permissions(ban_members=True)
@commands.hybrid_command()
async def ban(ctx, user: discord.User, *, reason="***No reason provided.***"):
""" Bans a user from the guild """
ban = discord.Embed(title=f" | Banned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}", color = discord.Color.brand_red())
await ctx.message.delete()
await ctx.channel.send(embed=ban)
bandm = discord.Embed(title=f" | You were Banned!", description=f"Reason: {reason}\nBy: {ctx.author.mention}")
await user.send(embed=bandm)
await ctx.guild.ban(user)
# UNBAN CMD
@commands.hybrid_command()
async def unban(ctx, user: discord.User, *, reason="***No reason provided.***"):
""" Unbans a user from the guild """
unban = discord.Embed(title=f" | Unbanned {user.name}!", description=f"Reason: {reason}\nBy: {ctx.author.mention}", color = discord.Color.brand_green())
hellowhat = discord.Embed(title=f" | {user.name} isn't Banned!", color = discord.Color.teal())
try:
entry = await ctx.guild.fetch_ban(discord.Object(user.id))
except discord.NotFound:
await ctx.channel.send(embed=hellowhat)
await ctx.guild.unban(discord.Object(user.id))
await ctx.channel.send(embed=unban)
await ctx.message.delete()
return
My bot doesnt see this code - I look in the help menu and there isnt a ban/unban cmd at all
even do +ban or +unban and nothing
terminal says command not found
How are these being added to the bot?
Also you really should not be making a thin wrapper over sensitive things that already exist while stripping away the security
just some normal code
like the rest of the cmds
just in the file
Show what is adding these commands to the bot
i have a sync command
Just declaring a command in the ether doesn't make the bot magically know about it
sync all the slash commands
well thats how all my others work
It's not
i think
There is something that adds those commands to the bot
which is?
I can't tell you how your code works that you haven't shown
Code that adds these commands to your bot
This code you sent declares a command. Nothing tells the bot that it exists, that you've shown
# SYNC SLASH COMMANDS WITH <prefix>sync
from typing import Literal, Optional
@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
i have this ig
thats my sync command
This tells discord about commands your bot knows about
This does not tell your bot about commands it doesn't know about
then what do I do to make my bot recognise them
ill take a docs link at this point i dont even need code
Please send the full file these commands are in
Compare these commands to the commands that are working
is there a way to get the raw message from an discord.Message? i mean json format like Message Object
i found on_socket_raw_receive and this is working but i still wonder is it possible to make it inside regular events eg on_message
firstly this exists
Look at the command decorator
There is a key difference between the one that works and the one that doesn't
even the docs show what im using
Post the two of them here, side by side. Just the command decorator. For one that works and one that does not
Working:
# UNHIDE CMD
@bot.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def unhide(ctx, channel : Optional[discord.TextChannel] = None):
""" Unhides the channel the command is used in, or a specified channel """
Not working:
# BAN CMD
@commands.hybrid_command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, user: discord.User, *, reason="***No reason provided.***"):
""" Bans a user from the guild """
oh
im stupid af-
i switched them between files tryna split it all up and didnt change it back
Sometimes I ask myself what's the purpose of a ban command
to enjoy the power you have
There isn't one besides pretending to be more useful than you are while reducing security
it was the @commands.hybrid_command() -> @bot.hybrid_command()
next is this fine and if it isnt how do i fix
And do you understand why those are different?
yeah
now what about this? @fast osprey
that's not an error
that's just a warning
You're just making a variable you never use
it means ure not using a variable ure declaring
Do you have an answer to my question above?
You would need to describe why it is you want the raw object
I want to send the raw message object to a third party server when the message is sent or edited
I can explain more specifically if you need
Hey so I made a cog names 'Configuration' and successfully added one command to it but when I try and add another it gives me a massive error - how do I add a command to an already made cog? Code below.
class Configuration(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# SYNC SLASH COMMANDS WITH <prefix>sync
@commands.hybrid_command()
@commands.guild_only()
@commands.is_owner()
async def sync(ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
# PING CMD
@commands.hybrid_command()
async def ping(ctx):
""" Replies with the Bot's latency """
await ctx.send(f"Pong! {int(bot.latency*1000)}ms")
Send the error
Error:
Traceback (most recent call last): File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 84, in <module> class Configuration(commands.Cog): File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 86, in Configuration @commands.hybrid_command() ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\hybrid.py", line 909, in decorator return HybridCommand(func, name=name, with_app_command=with_app_command, **attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\hybrid.py", line 509, in __init__ super().__init__(func, **kwargs) File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 406, in __init__ self.callback = func ^^^^^^^^^^^^^ File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 513, in callback self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 130, in get_signature_parameters raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)') TypeError: Command signature requires at least 1 parameter(s)
was already doing it lol
btw
removed cogs code from shown above
in the ping bit
you forgot to add self inside your sync command arguments
class Configuration(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# PING CMD
@bot.hybrid_command()
async def ping(ctx):
""" Replies with the Bot's latency """
await ctx.send(f"Pong! {int(bot.latency*1000)}ms")
this was my attempt but idrk
^^ in commands like this, you need self and ctx
ahhh ok
class Configuration(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# SYNC SLASH COMMANDS WITH <prefix>sync
@commands.hybrid_command()
@commands.guild_only()
@commands.is_owner()
async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
class Configuration(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# PING CMD
@commands.hybrid_command()
async def ping(ctx, self):
""" Replies with the Bot's latency """
await ctx.send(f"Pong! {int(bot.latency*1000)}ms")
got this now - shows on the ping command that self is not accessed
if im not mistaken I believe self comes before ctx
ohhhk
yep that was it
Awesome
new issue uhm only ping is shown in the cog: configuration
sync aint on there
class Configuration(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# SYNC SLASH COMMANDS WITH <prefix>sync
@commands.hybrid_command()
@commands.guild_only()
@commands.is_owner()
async def sync(self, ctx: commands.Context, guilds: commands.Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
class Configuration(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# PING CMD
@commands.hybrid_command()
async def ping(self, ctx):
""" Replies with the Bot's latency """
await ctx.send(f"Pong! {int(bot.latency*1000)}ms")
damn
sorry, the only thing I can think of is if you need to sync the command (with the text prefix) but i doubt thats the problem
thats only rlly for slash commands
One day two geniuses met 🤦♂️🤦♂️
@boreal sigil You defined two classes with identical names
but i want them in the same cog?
ohh i wasnt reading
you put all commands you want in one cog into the same class
So the ping command would go into the first Configuration class, then it would show both
@boreal sigil man its really annoying when people who havent learned python basics run to write discord bots and ask stupid questions
So basically take your ping command function, and move it into the first class called Configuration

This isnt helpful

awesome
now I do that for the rest of em
i already answered him above and just wrote this because its annoying
good luck :>
ty
What is "the message"? Who sent "the message"? Are they giving you explicit instruction to send their data to a third party?
# COG: GAMBLE. ROLL, COINFLIP
class Gamble(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# ROLL
@commands.hybrid_command()
async def roll(self, ctx, num: int):
""" Rolls a random number """
rollnum = random.randint(1, num)
rng = discord.Embed(title=f"{ctx.author.display_name} rolled a {rollnum}",
colour=0x00f5f1)
await ctx.send(embed=rng)
# COINFLIP
determine_flip = [1, 0]
@commands.hybrid_command()
async def coinflip(self, ctx):
""" Flips a coin """
flipping = discord.Embed(title="A coin has been flipped...",
colour=0x00b8f5)
flipping.set_image(url="https://i.imgur.com/nULLx1x.gif")
msg = await ctx.send(embed=flipping)
time.sleep(3)
if random.choice(determine_flip) ==1:
heads = discord.Embed(title="A coin has been flipped...", description=f"The coin landed on heads!",
colour=0x00b8f5)
heads.set_image(url="https://i.imgur.com/h1Os447.png")
await msg.edit(embed=heads)
else:
tails = discord.Embed(title="A coin has been flipped...", description=f"The coin landed on tails!",
colour=0x00b8f5)
tails.set_image(url="https://i.imgur.com/EiBLhPX.png")
await msg.edit(embed=tails)

You should put determine_flip into the function, otherwise the code can't find it
sometimes things are weird
yup - mess with code that works and get 1000 more errors
This is where OOP comes into play
Don't use time.sleep() it's not async
wait wut
it worked fine before?
It works, but it can cause problems
Yeah
it seems to work
read what I said again
If im correct that means that no other part of the script can be ran while the script is sleeping
yeah ik but its blocking
!blocking
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
very short is misleading, as it's not only the number inside sleep but how many tasks will queue up behind it and add onto the issue
If your bot manages many users in the future you will have problems
yeah it likely will
so does this just fix it? await time.sleep(3)
nope it doesnt
use asyncio
Use the asyncio module and then await asyncio.sleep()
thanks
works fine great
onto the next one
@dense falcon quick question how do you put spaces in a Cog name
eg. Channel Management
I believe there is an argument you can use to change the Cog's name to something like that, let me find it
ah alright thanks
class MyCog(commands.Cog, name=...)
ah ok

# COG: Channel Management. LOCK, UNLOCK, HIDE, UNHIDE
class MyCog(commands.Cog, name="Channel Management"):
def __init__(self, bot):
self.bot = bot
self._last_member = None
# LOCK
@commands.hybrid_command()
@commands.has_permissions(manage_channels=True)
async def lock(ctx, channel : Optional[discord.TextChannel] = None):
""" Locks the channel the command is used in, or a specified channel """
channel = channel or ctx.channel
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
if overwrite.send_messages is False:
alreadylocked = discord.Embed(title="Error!", description=f"The channel is already Locked!",
colour=0xf54242)
await ctx.send(embed=alreadylocked)
return
overwrite.send_messages = False
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
lock = discord.Embed(title="Channel Locked", description=f"The channel has been Locked!",
colour=0xe04d5c)
await ctx.send(embed=lock)
return
@lock.error
async def lock_error(ctx, error):
if isinstance(error,commands.CheckFailure):
await ctx.send('You do not have permission to use this command!')
else:
raise error
?
is there an error? do u need help? what are u asking

so i forgot to register it. await bot.add_cog("Channel Management"(bot)) used this and it aint working.
error 1:
c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py:34: SyntaxWarning: 'str' object is not callable; perhaps you missed a comma? await bot.add_cog("Channel Management"(bot))
error 2:
Traceback (most recent call last): File "C:\Users\a\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 449, in _run_event await coro(*args, **kwargs) File "c:\Users\a\Desktop\The Pikachu Crew\The Pikachu Crew Bot\main_code\script.py", line 34, in on_ready await bot.add_cog("Channel Management"(bot)) ^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'str' object is not callable
the bot.add_cog() method expects a Cog object. You must pass the class
thanks
Hello, I have a question about a distinction between a Discord bot vs a Discord app
#code-jam-participants-hangout message
This person says "you can use pure http interactions which doesn't require a Bot flow", would it make sense to learn that kind of thing before learning to make a bot? Is it easier?
You probably should start by looking at what you're trying to accomplish and then pick the best tool to accomplish it before considering what's easier
gateway bots are very good at doing a specific thing, but need to maintain websockets to do it
I don't have a specific goal in mind yet, just curious if I should learn one thing before the other. Or if it doesn't matter which one I choose
They do accomplish different things
Ok, I'll probably just start with a bot since I've seen more documentation on it
Thanks!
Hello
I have a small problem pls , I have code source of a verification bot , the verification redirect normally to a site wich is for the original bot , the bot I have now I want that when the person click on verify he got redirected on the same site the original one , idk a lot abt coding so anyone can come in dm I screen share the code and tell me if the option is already in it ( I’m not the person who developed the bot btw ) and thank you 🙏
my bot will be in only 1 server
@commands.Cog.listener("on_member_update")
async def on_member_update(self, before: discord.Member, after: discord.Member):
print(before, after)
pass
how will i know what changed ?, is by comparing is the only way?
Well what do you care about changing?
all of it
https://discordpy.readthedocs.io/en/stable/api.html?highlight=on_member#discord.on_member_update
in this timeout returns the int or async iterator?
Are you just logging everything that could possibly change for the sake of logging it?
you can compare the before.timed_out_until and after.timed_out_until to check timeout status
hmm
yeh kinda in a channel
why not just use the audit log
its far better
unless you're trying to log something the audit log doesn't
i doubt audit log leave anything apart from emoji
wdym
i mean adding emoji dont get logged in audit log
so why not just log that
and leave the rest to audit log
this really make more sense let me ask my friends
does message edit also get logged in audit log?
yeah you neednt worry about it, in only rare circumstances it will not work but if you want to be 100% fool proof you can still implement it
need help my bot and command etc now works but I have to press run every minute or so how do I fix it so it just runs?or at least for a while longer?
@ me if yk how to fix
Where are you running it?
def setup_news_commands(bot):
news_group = app_commands.Group(name="news", description="News related commands")
def has_staff_role(ctx): # Function to check if user has any staff role
# Fetch the member to ensure roles are up-to-date
member = ctx.guild.get_member(ctx.author.id)
if not member:
return False
user_roles = [role.id for role in member.roles]
matching_roles = [role_id for role_id in staff_roles if role_id in user_roles]
if matching_roles:
return True
else:
return False
@news_group.command(name="setreviewchannel", description="Set review channel for news articles.")
@commands.check(has_staff_role)
async def news_setreviewchannel(interaction: discord.Interaction, channel: discord.TextChannel):
try:
with open('main.json', 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = {}
data['review_channel_id'] = channel.id
with open('main.json', 'w') as f:
json.dump(data, f, indent=4)
await interaction.response.send_message(f'Review channel set to {channel.mention}')``` command works fine but even though someone doesnt have one of the staff roles they can still do the command
no errors
You should consider using the integrations menu to limit app commands rather than checking locally in code
Hello
I have a bot and when this bot is used I just want the user to see his command, I have almost no knowledge on how to do it.
the bot is in multiple servers thats why it needs to be limiteed in the logic
do you have any idea why thats not working?
ctx.author
yo manix u know how to solve my issue
I dont understand what your code does
its a group commands named 'news'
the commands work fine but the permission check isnt working
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure) exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
is is working right now?
just added it gonna check
Task exception was never retrieved
future: <Task finished name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() done, defined at /home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py:1149> exception=AttributeError("'Interaction' object has no attribute 'author'")>
Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1151, in wrapper
await self._call(interaction)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1310, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 879, in _invoke_with_namespace
if not await self._check_can_run(interaction):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 1017, in _check_can_run
return await async_all(f(interaction) for f in predicates)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/utils.py", line 704, in async_all
for elem in gen:
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 1017, in <genexpr>
return await async_all(f(interaction) for f in predicates)
^^^^^^^^^^^^^^
File "/home/container/commands/news.py", line 15, in has_staff_role
member = ctx.guild.get_member(ctx.author.id)
^^^^^^^^^^
AttributeError: 'Interaction' object has no attribute 'author'``` well it seems to be working but if i dont have the role it throws this error
@willow sluice
@news_group.command(name="remove", description="Remove a news registration")
@app_commands.check(has_staff_role)
async def news_remove(interaction: discord.Interaction, channel_id: str):
ensure_json_file('channels.json')
with open('channels.json', 'r') as f:
channels = json.load(f)
if channel_id in channels:
user_channel = bot.get_channel(int(channel_id))
guild_name = user_channel.guild.name
news_channel = bot.get_channel(news_channel_id)
del channels[channel_id]
with open('channels.json', 'w') as f:
json.dump(channels, f, indent=4)
await interaction.response.send_message(f"Channel ID {channel_id} has been successfully removed.")
await news_channel.send(f"**{guild_name}** - <#{channel_id}> has been removed from the newsfeed!")
else:
await interaction.response.send_message(f"The specified Channel ID was not found.")```
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
AttributeError: 'Interaction' object has no attribute 'author'
no like um if i write the command the bots shows the thing just for me
not for everyone
wait
@torn solar i agree its very difficult to write code YOURSELF
def has_staff_role(interaction: discord.Interaction):
return bool([i for i in staff_roles if i in interaction.user.roles])
are you using app_command or regular command with prefix?
app one
im new in python
i just write this code
@tree.command(name='kaydol',
description="Kaydolmak için kullanılır [kullanıcı_adı] [şifre]")
async def kaydol(interaction: discord.Interaction, kullanıcı_adı: str,
sifre: str):
f = open("keys.txt", "a")
f.write(f" | {kullanıcı_adı}, {sifre} | ")
em = discord.Embed(description=f"Başarıyla kaydolundu!", color=0x0025ff)
await interaction.response.send_message(embed=em)
its turkish
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None, poll=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
read docs
there is arg what you are looking for
i hope
this is statement and not question you will find it
i cant but i can show you what i want
how i made this type of message
?
this is default error when interaction didnt response
yea ik
i just want to show you this i need to my bot type like that only i see
i need the "Only you cann see this" thing
i got what you want and i send you link to docs
Can you read? There are only 10 lines
im really surprised by you and people like you its anoying
Thank you for your help, but since I didn't know exactly what I was looking for and the place you showed wasn't on the site I went to, I couldn't understand what you were saying, so I couldn't find it? What's annoying?
def setup_news_commands(bot):
news_group = app_commands.Group(name="news", description="News related commands")
def has_staff_role(interaction): # Function to check if user has any staff role
# Fetch the member to ensure roles are up-to-date
member = interaction.guild.get_member(interaction.user.id)
if not member:
return False
user_roles = [role.id for role in member.roles]
matching_roles = [role_id for role_id in staff_roles if role_id in user_roles]
if matching_roles:
return True
else:
embed = discord.Embed(title="No Permission", color=d_color, description="""
You do not have permission to execute this command!""")
interaction.response.send_message(embed=embed)
return False
@news_group.command(name="setreviewchannel", description="Set review channel for news articles.")
@app_commands.check(has_staff_role)
async def news_setreviewchannel(interaction: discord.Interaction, channel: discord.TextChannel):
try:
with open('main.json', 'r') as f:
data = json.load(f)
except FileNotFoundError:
data = {}
data['review_channel_id'] = channel.id
with open('main.json', 'w') as f:
json.dump(data, f, indent=4)
await interaction.response.send_message(f'Review channel set to {channel.mention}')
``` the check is working although its not sending the embed saying no permission and if they dont have the permission it throws an error in console so how can i handle it correctly
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1310, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 880, in _invoke_with_namespace
raise CheckFailure(f'The check functions for command {self.name!r} failed.')
discord.app_commands.errors.CheckFailure: The check functions for command 'remove' failed.``` this is the error
So one thing you could do is limit this on permission and have individual guilds choose if they want a specific role. What you have now is pretty inflexible if people decide they want to change things, and plus it still lets users see the command when you could prevent them from running it in the first place
so basically how it works is the bot is in other servers just to read messages and relay them to the news channel
i have the permissions working
i just need to know how to handle the error
I mean you do you, but discord has given you a system for managing permissions, and you're writing extra code to go around it
did you google?
you will be very surprised when you find out how much useful information is in google and discord.py docs
i figured it out
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='?', intents=discord.Intents.default())
@client.event
async def on_ready():
print("Bot is up")
@client.command()
async def hello(ctx):
await ctx.send("hello, world")
client.run('TOKEN')
anyone have any idea why I'm getting invalid syntax, chatgpt isn't giving really a reason
there should be error in console pointing to line
give me screenshot of error
💀
quick question: is d.py still the most popular framework? Or are forks now more popular?
how would I get it the bot to actually print out "hello, world" into the chat?
like do I do /hello?
or !hello?
how tf do i shut down a bot
nvm it's ?hello
This would result in a warning
it doesn't 🤷
async def on_error(self, interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
if isinstance(error, discord.app_commands.errors.CheckFailure):
embed = discord.Embed(title="No Permission", color=d_color, description="""
You do not have permission to execute this command!""")
await interaction.response.send_message(embed=embed,ephemeral=True)
else:
raise error``` tried to do this to handle this error below
```Traceback (most recent call last):
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/tree.py", line 1310, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.12/site-packages/discord/app_commands/commands.py", line 880, in _invoke_with_namespace
raise CheckFailure(f'The check functions for command {self.name!r} failed.')
discord.app_commands.errors.CheckFailure: The check functions for command 'remove' failed.``` but its still not handling the error
how did you add your error handler to the tree?
class DemocracyUtilsBot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
super().__init__(command_prefix="?!", intents=intents)
async def on_ready(self):
print(f'Logged in as {self.user}')
await self.change_presence(activity=presence, status=status)
setup_news_commands(self) # Setting up news commands
async def on_message(self, message):
# Process message here
await self.process_message_for_webhook(message)
await self.process_commands(message)
async def on_error(self, interaction: discord.Interaction, error: discord.app_commands.AppCommandError):
if isinstance(error, discord.app_commands.errors.CheckFailure):
embed = discord.Embed(title="No Permission", color=d_color, description="""
You do not have permission to execute this command!""")
await interaction.response.send_message(embed=embed,ephemeral=True)
else:
raise error``` its inside my bot class
oh, Bot.on_error isnt the same as the tree's on_error
i'd suggest naming your method to something else and then using self.tree.error() to register it on your tree, e.g. ```py
class MyBot(commands.Bot):
def init(self):
super().init(...)
self.tree.error(self.on_tree_error)
async def on_tree_error(self, interaction, error):
...```
ill try this
this worked btw forgot to respond ty
(disnake) what flow of interactions should I use if I am sending a View in my message and later need to set a message attr to the view (so that I can disable the view on timeout and edit the message with the updated view)
class PaginatorView(disnake.ui.View):
message: disnake.Message
async def on_timeout(self) -> None:
for child in self.children:
child.disabled = True
await self.message.edit(view=self)
basically what I'm asking is how should I respond to the slash command interactions to be able to get the disnake.Message object
Don't set it as a class variable, set it as an instance variable
And when sending the view attach the message object there
view = PaginatorView()
msg = await ctx.send(view=view)
view.message = msg
Something like this
That's what I'm doing, my question is how to get the msg object u used here, with slash commands
I'm not good with slash commands
I'll test it once I can, thanks
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
try:
await bot.load_extension('cogs.shift')
await bot.load_extension('jishaku')
await bot.load_extension('cogs.fun')
await bot.load_extension('cogs.utility')
await bot.load_extension('cogs.moderation')
print('Cogs loaded successfully')
except Exception as e:
print(f'Failed to load cog: {e}')```
Error: Failed to load cog: No module named 'cogs'
Do you have init.py?
uh.. no
Could that be
What do I put In It?
You can leave it empty
Still get the error
hey , how can i get info about another user , other than the author of the command ? like !command @mention , so i should get , info about both , author and the user the author mentioned
async def serverinfo(self, ctx):
guild = ctx.guild
embed = discord.Embed(title="Server Info", description=f"Information about {guild.name}", color=0x00ff00)
embed.set_thumbnail(url=guild.icon.url)
embed.add_field(name="Server Name", value=guild.name, inline=True)
embed.add_field(name="Server ID", value=guild.id, inline=True)
embed.add_field(name="Owner", value=guild.owner, inline=True)
embed.add_field(name="Region", value=guild.region, inline=True)
embed.add_field(name="Members", value=guild.member_count, inline=True)
embed.add_field(name="Roles", value=len(guild.roles), inline=True)
embed.add_field(name="Channels", value=len(guild.channels), inline=True)
embed.add_field(name="Created At", value=guild.created_at.strftime("%Y-%m-%d %H:%M:%S"), inline=True)
await ctx.send(embed=embed)```
thx for the help , let me try and understand that
what's your current command lookin like?
Everything u can guess. So member count of the server Is guild.member_count
async def userinfo(self, ctx, member: discord.Member = None):
member = member or ctx.author
embed = discord.Embed(title="User Info", description=f"Information about {member}", color=0x00ff00)
embed.set_thumbnail(url=member.avatar.url)
embed.add_field(name="Username", value=member.name, inline=True)
embed.add_field(name="Discriminator", value=member.discriminator, inline=True)
embed.add_field(name="ID", value=member.id, inline=True)
embed.add_field(name="Status", value=member.status, inline=True)
embed.add_field(name="Top Role", value=member.top_role.mention, inline=True)
embed.add_field(name="Joined Server", value=member.joined_at.strftime("%Y-%m-%d %H:%M:%S"), inline=True)
embed.add_field(name="Account Created", value=member.created_at.strftime("%Y-%m-%d %H:%M:%S"), inline=True)
await ctx.send(embed=embed)```
This iS how to get user Info
The other one was server
i am just learning , it so its just my 2nd day on discord.py , just was thinking about how will i do that
thx , i ask if i face any problems
Alright. Do @bot.command
For yours
As Im using cogs without the @bot stuff.
ya , i will do that , and i should also remove the self parameter
don't spoonfeed 😭
Its a better way to learn In my opinion.
fair
Do what you think. Thats just what I have try and edit It to your likings.
yes thats what i am trying to do by understanding , what the code is doing before using it
thx i understood most of it
can i explain this member:discord.Member:None whats None parameter does in it
Represents a Discord member to a Guild.
This implements a lot of the functionality of User.
Attributes
joined_at: Optional[datetime.datetime]
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
activities: Tuple[Union[BaseActivity, Spotify]]
The activities that the user is currently doing.
this i what vs code says , but its not clear enough for mw
me*
It's the same thing as doing : discord.Member | None = None in dpy
But you can default to the command author here instead of None and handling it in the callback:
member: discord.Membed = commands.Author
how i get the user id with tree command?
Interaction.user is an instance of Member/User
thankss
Hello again.
How can I create a txt file in the folder named "users" for my bot?
What is this txt file being used for?
extremely late but You can do this with the open() function, which (when given correct parameters) will create a file with the name you choose. For example:
file = open("example.txt","w") - Creates a file if it doesnt already exist, otherwise it modifies the file
or instead of using w, use x, which can only create a file and returns an error if it already exists
needs a prefix
and how do i do that
add a command_prefix= parameter
Thankss!
and how i bot can create file in the folder which i selected
make it a string and remove the parenthesis
how i make it a string
command_prefix="!"
open("folder/file.txt")
i js added
Show where you're putting the code
you'll want something like this:
bot = MyBot(command_prefix='!', intents=intents)
You ended up defining bot twice
thanks
Well firstly for your deleted screenshot, Slash Commands are referred to as app_commands
uh can you show the code that's having the error
``@bot.app_commands(guild_ids=[settings["guildID"]], name="whitelist", description="Whitelist a person to use the bot.")
async def whitelist(ctx: discord.ApplicationContext,
user: discord.Option(discord.Member, "Member to whitelist.", required=True)):
if not isAdmin(ctx):
return await ctx.respond("Only Bot Admins can use this command.")
settings["botWhitelistedId"].append(str(user.id))
json.dump(settings, open("settings.json", "w", encoding="utf-8"), indent=4)
return await ctx.respond(f"*{user.mention} has been whitelisted.*")``
what's the code for settings? how is it defined
``{
"capmonsterKey": "CAP-25C663138AF0088A8990B793EF92B0B1",
"botToken": "Token",
"guildID": "1260963242428207284",
"botAdminId": [
"741839840110182441"
],
"botWhitelistedId": [
]
}``
Uh its not working :(
that is returning the user object, you'll likely want to use user.name or user.id
just a sec lemme do some checks
like this but with bot
f"users/{member}.txt"?
OK so guild_ids is not a valid parameter for an app command
what do you want it to do?
its a boost bot
whats that
the closest I can think of for this is you want the bot's slash commands to work in the guild
yes
ok remove the guild_ids parameter in the decorator
in settings?
@app_commands.guilds(discord.Object(id=GUILD_ID_GOES_HERE))
im confused, can u help me if i send the code?
What are you trying to do with this parameter
by default app commands are global and available to all guilds the bot is in
you see this
@bot.app_commands(guild_ids=[settings["guildID"]], name="whitelist", description="Whitelist a person to use the bot.")
change it to this
@bot.app_commands(name="whitelist", description="Whitelist a person to use the bot.")
successfully removed guild_ids parameter
Oh and in doing this, the slash commands will ONLY work in the given server. This does speed up tree syncing a lot though so it can be a good tradeoff if nowhere else uses it
It doesn't
what is bot.app_commands?
it does something a lot faster though, cant remember what
There used to be a delay on global syncing more than a year ago
use @bot.tree.command()
i might have been thinking of commands.command() or something probably
I use hybrid commands so I kinda forgor the rest
there's also @app_commands.command
ah that's the one
is there a way to ensure task loop only start after the bot start?
so if i understand correctly the major differences between REST api and gateway is
- REST api only revices interaction events
- Gateway api can receive all intents that the bot is registred for
- REST api does not need a always alive connection
- purely interaction based "apps" can be made in both http and gateway
is this all ?
task loop ?
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
this thing
when my bot loads sync loop starts before on_ready
as i am calling it on constructor is there a way to ensure it only starts after on_ready?
You can use wait_until_ready() But I'm not sure
it will be called automatically?
wait_until_ready is a utility that yields until the bot is ready. Nothing calls it, you would use it in some task you wanted to wait
Hmmm I don't use discord.py but I saw that in the documentation
There's a very common pattern to await wait_until_ready inside of a task loop's before_loop. Then you can start it wherever you want
in fact, this is done in one of the recipes in the official docs
where should i use this? inside task loop directly?
in before_loop
ok
why api fetching is not after bot login?
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
What do you mean by "api fetching"?
fetching data from api
i want on_ready to fire first and then api fetching should start
You should not be using on_ready to drive logic
so bot have all the things in its cache
i am not using it
wait_until_ready this thing
You just said you wanted on_ready to fire. Why do you care about that event
You're using wait until ready. That will yield after the cache is populated. What makes you think it isn't?
i want on_ready to fire so my bot have cache and all things load up
oh
Again. On_ready is not what you want or care about here
When the cache is populated, a few things happen and the ordering of them isn't guaranteed
on_ready will fire but not necessarily before or after wait_until_ready yields
actually what i am doing is , i am hitting api every 5 minutes if the data change i changes role according to that so when bot gets online and it checks sometimes it doesnt remove the roles
What api?
its a private game api developed by my friend
Ah. Ideally they'd implement a pubsub method to reduce load for both of you but for private stuff it's whatever
You subscribe to this service, and it pushes relevant changes to you
Rather than you having to ask every 5 minutes
oh
i will definately look into this
really looks like a neat concept
It's advanced and not needed on this scale probably but interesting to learn
: ) ty for suggestion
how to make a inventory system without mangodb? i just coded little but its not working
If you're tracking dynamic data generated by your application, you absolutely should be using a database and not writing to flat files yourself
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
any feedback would be helpful
i know
it's not the same
but i have no clue how to do that xd
testing text i guess
No the 'This user Is suspected of pirating music online'
any feedback would be helpful
-# This user Is suspected of pirating music online
-# t
Discord mobile can't render it tho lol
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/5ZTA
Traceback (most recent call last):
await item.callback(interaction)
await self.show_page(interaction)
message = await interaction.response.edit_message(embed=embed)
AttributeError: 'Button' object has no attribute 'response'
im lowkey rusty at coding but i remember this used to happen when trying to edit messages/embeds with buttons involved but idk how to fix it
You are most likely using dpy as a library while following a tutorial made for another library
if I use nextcord instead of discord.py will I still be able to use all of the regular discord.py functions?
cuz I'm getting this:
DistributionWarning: discord.py is installed which is incompatible with nextcord. Please remove this library by using pip3 uninstall discord.py
You should pick one
yeah I'm asking if I remove discord.py
will I still be able to use like
@client.command()
@commands.is_owner()
async def shutdown_bot(ctx):
await ctx.send("Shutting down...")
print("Shutting down...")
await client.close()
it may be a bit different
or do I have to figure out how to do it in nextcord
but nextcord is a fork so the commands stuff should be mostly the same
Can't tell you how much forks have diverged, or how much they will continue to diverge
from what i can tell the interactions stuff differs a fair bit more
ok
you will have to read the docs and figure that out
thanks
https://paste.pythondiscord.com/QLRA
Can someone help me put pagination on this? I've been trying for a couple of hours but it just keeps giving me error so i restarted it without the pagniation
Error?
js keeps saying button has no attribute to response
Please follow these examples
Also, app commands do not receive a context. You should not be calling the parameter ctx
https://paste.pythondiscord.com/TNHA
i did this and it doesnt give me errors but it just doesnt do anything interaction failed
Are you logging anything?
There is code here which would definitely cause an error
And when you say you get interaction failed, that happens when?
when i click either of the buttons
and no idk what to log tbh
yes its a command
But you're saying the failure is happening with a button
Please. Read the examples I sent
and start from those
i did but ill do it again ig
You did not
Your view looks different from the examples. You should START from the examples, not try and pinpoint differences off of whatever you started with
because i didnt use the examples i read it and i didnt understand so i js did it my own way and it didnt work
You started with examples/tutorials someone made for another library
does anyone have a GitHub link to a working up to date multipurpose bot that i could directly clone into vs code and add a token and run?
maybe redbot
bedsides redbot?
you know anything besides
@obsidian dune
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
await bot.process_commands(message)
@bot.command()
async def hello(ctx):
await ctx.send('Hello!')
bot.run('token')
very multipurpose
wowo
omg
is it normal that when syncing slash commands in takes a long time before it appears on discord?
Nope it's basically instant
Sometimes you have to reload your client, or you're not syncing what you think you are
ok thx
Hello, i have this code:
@bot.event
async def on_guild_channel_create(channel, ctx):
# Check if the channel name starts with "bitcoin", "litecoin", or "eth"
if channel.name.lower().startswith(("bitcoin", "litecoin", "eth")):
unique_id = f"zxczxczxc"
await ctx.send(unique_id)
asyncio.sleep(1)
await ctx.send("Send us user id of guy you're dealing with!")```
How should i add bot.event to detect next message that user will send(User id), if it's valid user id from server then overwrite his permissions to read and send messages in channel
dont mind unique id i wrote it manualy for sending it here because it was messing up backsticks message
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError) for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple) containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
see the example in the docs there for waiting for a message
having a problem getting to use prefix and slash commands onto the same bot
You want to use prefix command or don't want to use?
i have slash commands but the prefix commands dont work for some reason
If u have @app_command then I don't think it will work for normal commands
It will only work for slash
i have it like this
@bot.tree.command(name="test")
ye i want slash and prefix also
For same command?
Then don't add that to tree then it should work i belive ,I have not tried it myself but it should work iirc
alright
If u add that to tree then I belive it will be added to slash category
use hybird commands then
it is the same command but can be slash or prefix
I need some help I have loads of cogs but when I load them I get a error saying the folder does not exist.
Wait
Nvm I fixed It
Interactions are mostly menus butons or slash commands.
so stuff like !userinfo is just command?
which display userinfo formatted
Yes. But you can have /userinfo
They are the same thing
type /
and you can see slash commands
You cant do that for commands
No?
Or I dont think
I dont rlly user interactions
like if i do /ping
how is slash commands different from like if i make a command using Command and make command_prefix /
or is there a class for slash commands
then it will be a prefix command and won't use interactions
Slash command is application commands and if the prefix is / then there will be no interactions.
Prefix commands are not recommended tho personally
Anyone wanna join a bot team dm me 🙂
There's a whole list of things that slash commands support which prefix don't and vice versa. They are two separate systems with different behavior really
not sure I understand this
works for the other prefix commands
this is the whole thing:
#help/list command
@bot.command()
async def help(ctx):
embed=discord.embed(
colour=discord.Colour.blue(),
description="\n1. ping\n2. hi\n3. hello\n4. inspire\n5. dog\n6. cat",
title="Command List",
timestamp=current_time
)
await ctx.send("\n", embed=embed)
nvm got it, changed help to command
dpy bots ship with a default help command
Probably does what you want but cleaner. You can augment it if you want to change how it displays
hmm, would you happen to know where I can read up more
Other option being moving to slash commands which are largely self documenting
thanks a lot, I'll go through this
reaf my discryption

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id
@client.command(name='testban')
@commands.guild_only()
async def testban(ctx, member: discord.User = None):
try:
server_ban = await ctx.guild.fetch_ban(member.id)
if server_ban:
await ctx.send("Found banned user.")
except discord.NotFound:
await ctx.send("User is not banned from the server.")
!d discord.Guild.fetch_ban
await fetch_ban(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry) for a user.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members) to get this information.
Do you actually know what's causing the issue?
Yes, and the reviewing the documentation for the method you're using should make it clear what the issue is
I still don't get it
Read the documentation, and check the expected inputs and outputs
compare what you are passing into the method with what the documentation says you should be
I already did
So
- What are you passing into fetch_ban
- What does the documentation say you should be
It says to use an ID which I did
It does not
Review the Parameters section of that method
It tells you the type it wants
user (abc.Snowflake)
Yes. That is not an integer
You'd want to get a user from the ID using get_user() or fetch_user()
then put that into fetch_ban
Snowflake is a type. It isn't just a fancy way of calling an integer
(You already have a Snowflake)
They don't need to get or fetch a user, given they already have one
ah yeah pass member into it or smth
ctx.guild.fetch_ban(member)
I'd try it ye
Could I also use something like ctx.guild.fetch_ban(discord.Object(member.id))
probably, but why?
Or that would be the same as member
that would be the same as member
since member is a discord.User, getting the object with member's ID would just return the same user
Oh, I see thanks. I'm still confused why it says to use Snowflake, and when I do it gives me an error?
Snowflake is a base type. It's just a holder for a discord object id. Other types (like user, member, channel, guild) implement it
Got it now. So I was using an id from an integer that doesn't exist
You weren't. The library was. It was expecting you to give it a Snowflake, which it would assume has a .id attribute
Mhm
how should i use discord.py to add buttons to my discord embed, didnt code bots for long now, and my bot got verified not long ago so i have to hop on updates 🙂
there's button examples in the repo
An error occurred: expected Item not tuple
if user:
await channel.set_permissions(user, read_messages=True, send_messages=True)
await channel.send(f"@{user}")
embed = discord.Embed(title="Example Embed", description="This is an example embed with buttons", color=0x37f563)
view = discord.ui.View()
style = discord.ButtonStyle.gray
styledanger = discord.ButtonStyle.danger
item = discord.ui.Button(style=style, label="Sender"),
item1 = discord.ui.Button(style=styledanger, label="Receiver"),
item2 = discord.ui.Button(style=style, label="Reset")
view.add_item(item=item)
view.add_item(item=item1)
view.add_item(item=item2)
await channel.send(embed=embed, view=view)```
What's up with this error huh
when im pulling/pushing from vscode to github and i have databases that i edited do i just not do it or what
just not do what?
your first two item lines have a trailing comma at the end, that implicitly puts them inside a tuple
!e py x = "Hello world!", print(x)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
('Hello world!',)
yeah, those trailing commas are the cause
also i would suggest defining buttons using the decorator style instead, that'll make it easier to write callback functions for them: ```py
class MyView(discord.ui.View):
@discord.ui.button(label="Greet", style=discord.ButtonStyle.primary)
async def greet(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(f"Hello there, {interaction.user.mention}!")
To use:
view = MyView()
await channel.send(..., view=view)```
Ohh will keep in mind
i would really like someone
to teach me on how to learn python and discord bots and tools etc
whoever is very advanced and has day to day time to teach i will really appreciate it, small payment at the end
Rule 9
Do not offer or ask for paid work of any kind.
Rules 8
@fast osprey
Well that's not very nice
do u code discord bots

Well for starters, I had 7 years of industry python experience under my belt
that isnt telling me how u start..
I started by learning programming fundamentals, which I did at a 4 year full time university
im looking for basic python lessons for starters, tips i am looking for
oh hell nahh
how old is u my boy 💀
Pretty probing question from an online rando
I'm not the one doing anything, trust me
just where did u go to learn fundamentals
👍
From university courses and text books
oh hell no
so u cant learn it online?
all i really want to know is how to make like discord bots and databases and shi
And you will need programming and python fundamentals before you do that
the official python docs are pretty good, though they do rely on some base programming knowledge
where i get them
and what is minimum age to learn all this. can u learn at a young age
Googling python docs is a good start
thanks
These concepts build on top of each other and take time to learn, so if you're starting from scratch this is an investment
look
commandmenu = ' HELLO WORLD '
print (commandmenu)
I am learning so much LOL
this is the only thing that seems to make sense in my head
This may be a super silly question but. Is it by any chance possible to make a bot that can edit google sheets?
Or at the very least, read and take the values of a google sheet?
yeah
Then, is it possible to make it so the bot can edit one google sheet using the values of another google sheet? (Lets say member 1 uses their own sheet to use a command that changes the values of member 2’s cell d:6 using the value of member of member 1’s cell d:4. Or maybe even a formula using said values?)
Mkay.
Or you could just do
print("Hello World")
Is there a way to find out inviter user id of the specific user in the guild besides scraping the whole response from https://discord.com/api/v9/guilds/{guild_id}/members-search?
@app_commands.command(name="testcommand", description="A Test command")
@guild_only()
async def testcommand(self, interaction:Interaction, user_input_1:str, user_input_2:int) -> None:
await interaction.response.send_message("Hello World")
What would be the javascript equivalent to this? My friends trying to make a bot in javascript and IDK javascript ;-; im hoping someone here can help lol
Asking how to make something in js really isn't in the remit for the Python server
ctx.guild.members returns list of all members?
My cogs dont work help
just use the members tab
unless you're doing some sort of leaderboard tracking thing
there are many reasons cogs don't work
Failed to load cog: Extension 'cogs.input' has no 'setup' function.
does your input cog have a setup function?
async def setup(bot):
await bot.add_cog(input(bot))
can you show the whole code
Im testing smth for another bot.
from discord.ext import commands
# Create a bot instance with a command prefix
bot = commands.Bot(command_prefix='!')
# Dictionary to store log channels per server (guild)
log_channels = {}
class input(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def logchannel(self, ctx, channel_id: int):
# Try to fetch the channel by ID
channel = self.bot.get_channel(channel_id)
if channel:
# Store the log channel for the current guild
log_channels[ctx.guild.id] = channel_id
await ctx.send(f'Log channel has been set to {channel.mention}')
else:
await ctx.send('Invalid channel ID. Please provide a valid channel ID.')
@commands.command()
async def log(self, ctx):
# Get the log channel for the current guild
channel_id = log_channels.get(ctx.guild.id)
if channel_id:
channel = self.bot.get_channel(channel_id)
if channel:
await channel.send('A log has been created.')
else:
await ctx.send('Log channel not found.')
else:
await ctx.send('Log channel is not set. Use !logchannel <channel_id> to set it.')
async def setup(bot):
await bot.add_cog(input(bot))```
where is your bot.load_extension
from discord.ext import commands
import sqlite3
# Database setup
conn = sqlite3.connect('shifts.db')
cursor = conn.cursor()
# Bot setup
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')
try:
await bot.load_extension('cogs.shift')
await bot.load_extension('jishaku')
await bot.load_extension('cogs.fun')
await bot.load_extension('cogs.utility')
await bot.load_extension('cogs.moderation')
await bot.load_extension('cogs.input')
print('Cogs loaded successfully')
except Exception as e:
print(f'Failed to load cog: {e}')
bot.run('Token')``` This is In my bot.py
and this is your input.py?
Yes.
this is with discord.py 2.0 right? weird that it didnt tell you a different error since the commands.Bot(command_prefix='!') declaration inside your extension module should have raised a TypeError for missing the intents= argument
yeah i'm not sure it's 2.0
it would explain the setup function not found
though, shouldn't it say it's not a function or similar?
@limber jolt can you get us your discord.py version?
same thing with load_extensions, it should be giving them a NoneType is not awaitable error 
but if it was able to load the other extensions without that error, it likely is dpy
Alright
discord.py or discord?
in which case there should have been a different exception for failing to load the module, so perhaps input.py just isn't saved?
It should be i left It for like a whole day
err both shouldnt be installed at the same time
do you have any other libraries like nextcord or py-cord? those would conflict too
They are same thing.
no
SOrry If I sound stupid just woke up
you may wanna double check, if you aren't using a venv it can conflict from other projects if you installed another library in the past
pip list lists all packages
discord might be a mirror of discord.py, but they overwrite each other's files which can occasionally result in some obscure bugs
Oh it's there cool
mfw you pip installed discord.js
Is it possible to accept attachment with slash commands? Or any other attachment?
As I do both
i think slash commands do support attachments
Cool
just pointing out, you pip installed (pip is a Python package manager) a JS library
It will be in bytes format right?
I removed It
from discordjs import Client
from javascript import console
client = Client()
client.on("ready", lambda:
console.log("Bot is ready")
)
async def msg(message):
if message.content.startswith("!ping"):
await message.channel.send("pong")
client.on("message", msg)
client.login('Token')
this is kind of funny
someone tried to recreate discord.js in python
dont worry, that discord.js package looks like its missing its own module anyway
oh its by one of those youtube discord bot tutorial people
I removed discord.js and i still get error
If u r in vsc kill terminal and reopen new one and then try
already tried. Same error

idk
@sick birch Its still not owrking 😭
working*
<@&1262112129818034268>
<a:f:1261728256348913725>
Please click on the button below to get the sync time.
:alert: Note - You can only check sync of one league only.
2024-07-18 12:00:25 ERROR discord.ext.tasks Unhandled exception in internal background task 'my_task'.
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.12\Lib\site-packages\discord\ext\tasks\__init__.py", line 241, in _loop
await self.coro(*args, **kwargs)
File "D:\AFW bot\afw_bot\ext\auto_sync_update.py", line 142, in my_task
await message[0].delete()
File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.12\Lib\site-packages\discord\message.py", line 1001, in delete
await self._state.http.delete_message(self.channel.id, self.id)
File "C:\Users\HP\AppData\Local\pypoetry\Cache\virtualenvs\afw-bot-0qM92z9o-py3.12\Lib\site-packages\discord\http.py", line 754, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
await message[0].delete()
how this can print content but when calling .delete() it fails?
another thing i would like to ask how frequently message data get cached?
wdym frequently? it gets cache as soon as on_message event gets fired
that message was probably deleted before you had the time to delete them, delete(delay=0) would put it in a task which suppress error btw
try to send and delete 5 times in a row very frequently
got it
another thing i would like to ask i am trying to log deleted messages with on_message_delete how will i go for embed logging? like should i send full embed which got deleted?
would just store the dict of that embed, embed.to_dict()
another thing i would like to ask , does the event tells who deleted the message?
nothin, you have to use audit log through guild.audit_logs
is there any event which tells?
nope, people would usually use audit logs inside on_message_delete
oh u mean audit logs is a method inside it?
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the guild’s audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log) to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
oh i thought app audit log u r talking about
this thing tells who deleted the messages and how many it did?
how can i get number of message deleted? with just on_message_delete?
nop use on_bulk_message_delete
: ( i will ask my friend to use audit logs
oke
how do u fix numpy not avalible
@bot.command()
async def create_thread(ctx):
channel = ctx.channel
thread = await channel.create_thread(name="My Thread", reason="Thread created by bot command")
await ctx.send(f"Thread created: {thread.mention}")
when i use the command, the bot just create an "#unknow" thread, i think because it a private thread, how do i make it public?
!d discord.TextChannel.create_thread
await create_thread(*, name, message=None, auto_archive_duration=..., type=None, reason=None, invitable=True, slowmode_delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a thread in this text channel.
To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_private_threads) is needed instead.
New in version 2.0.
Either create it off a message or specify in the type parameter
Why this happens:
Explanation:
- I click button
- It sends Confirmed because it was coded to send that, but button still loads like it wasnt clicked
- Shows error "This interaction failed"
Why does it show error if it did what i coded it to do
That means you aren't responding to the interaction
You should be using be interaction.response.send_message
Hi I am just a newbie in python but I decided to make a project which will be verifying users and then giving them a role
Like when users join my server they can't message until they go to app link and verify I have seen this in many big servers and want to learn how it works
But I couldn't find it
This entirely depends on what exactly you're verifying about them
Verifying that they're a human? That they've read some rules? That they have the email they say they do? etc etc
They are human and also fetching their email IDs and storing them as CSV when they authorise
I once Manage to get email IDs but couldn't implement verify system
It is prohibitively difficult for you as an individual to verify if someone is a human. If you want to do this effectively, you will need to integrate with an interactive captcha service or the like
import discord
class confirmview(discord.ui.View):
def __init__(self, reset_callback, currency):
super().__init__()
self.reset_callback = reset_callback
self.sender_confirmed = False
self.receiver_confirmed = False
self.sender = None
self.receiver = None
self.currency = currency
@discord.ui.button(label="Correct", style=discord.ButtonStyle.success)
async def correct(self, interaction: discord.Interaction, button: discord.ui.Button):
if len(interaction.message.mentions) >= 2:
if interaction.user == interaction.message.mentions[0]:
self.sender_confirmed = True
self.sender = interaction.user
elif interaction.user == interaction.message.mentions[1]:
self.receiver_confirmed = True
self.receiver = interaction.user
self.correct.disabled = True
self.incorrect.disabled = True
if self.sender_confirmed and self.receiver_confirmed:
await self.confirmation_complete(interaction)
else:
embed = discord.Embed(description=f"{interaction.user.mention} has responded with 'Correct'", color=0x37f563)
await interaction.response.send_message(embed=embed)
@discord.ui.button(label="Incorrect", style=discord.ButtonStyle.secondary)
async def incorrect(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.reset_callback(interaction)
await interaction.message.delete()
async def confirmation_complete(self, interaction: discord.Interaction):
embed = interaction.message.embeds[0]
embed.title = "Confirmed Role Identities"
embed.description = "Both users have confirmed their roles within this deal."
embed.set_field_at(0, name=f"Sending {self.currency}", value=self.sender.mention, inline=True)
embed.set_field_at(1, name=f"Receiving {self.currency}", value=self.receiver.mention, inline=True)
self.clear_items()
await interaction.message.edit(embed=embed)
deal_amount_embed = discord.Embed(title="Deal Amount", description="Please state the amount we are expected to receive in USD. (eg. 100.59)")
await interaction.message.channel.send(embed=deal_amount_embed)
Why it doesnt work?
i mean i want it to edit embed, remove buttons from it and send deal amount (new) embed after both people clicked correct button
and if one person clicked correct button disable it for that person
hewp 
you need to describe what doesnt work about the code
litteraly what i wanted to do doesn't work
these listed stuff.
i am not even sure if i coded it right
but it comes to this stage:
now it should remove buttons, edit that embed on top and send new one
when you change the button attributes, you need to edit the message with your current view so it get reflected on discord
so in your confirmation_complete where you had self.clear_items(), just do await interaction.message.edit(embed=embed, view=self)
or better yet, just set the view to None that will do the same thing by removing the view from the message
PLEASE HELP MEEE. This stupid cog IS taking forever to load. Theres nothing wrong with It at all
the buttons are showing interaction failed
message.txt: https://pastecord.com/akulonyriv
wait are you defining the class inside your command...?
The view class should be separate, and it internally should be declaring/adding whatever items it has
U talking to me?
yeah, read what solstice said
from discord.ext import commands
# Create a bot instance with a command prefix
bot = commands.Bot(command_prefix='!')
# Dictionary to store log channels per server (guild)
log_channels = {}
class input(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def logchannel(self, ctx, channel_id: int):
# Try to fetch the channel by ID
channel = self.bot.get_channel(channel_id)
if channel:
# Store the log channel for the current guild
log_channels[ctx.guild.id] = channel_id
await ctx.send(f'Log channel has been set to {channel.mention}')
else:
await ctx.send('Invalid channel ID. Please provide a valid channel ID.')
@commands.command()
async def log(self, ctx):
# Get the log channel for the current guild
channel_id = log_channels.get(ctx.guild.id)
if channel_id:
channel = self.bot.get_channel(channel_id)
if channel:
await channel.send('A log has been created.')
else:
await ctx.send('Log channel not found.')
else:
await ctx.send('Log channel is not set. Use !logchannel <channel_id> to set it.')
async def setup(bot):
await bot.add_cog(input(bot))```
What is leading you to believe this is taking time
As all my other ones have taken a day and then they work but this one has been taking awhile
can some1 help fix RuntimeError: Numpy is not available
What exactly is taking a day, and how are you narrowing it down to it being caused by this code?
For the cogs to work. ANd Its being caused by It bc when I run my bot.py i get this error
Failed to load cog: Extension 'cogs.input' has no 'setup' function.
And is the above the cogs.input module? That doesn't seem right
@client.event
async def help(ctx):
await ctx.send("Here are the available commands\n")
how would I edit this cuz when I do !help in my server I get
No Category:
check_channel
help Shows this message
shutdown_bot
Type !help command for more info on a command.
You can also type !help category for more info on a category.
The library has a default help command already, which is what you're seeing
thanks
So what would hte correct code be?
Thats what Im saying
Does the code you sent belong to a file called input.py that lives in a subfolder named cogs
Yes

You may need to import cogs.input and inspect the module, because it doesn't seem to be what you think it is
erm...
How od i inspect It?
Do*
import x
print(x.__file__)
print(x.setup)
PS C:\Users\willi\Desktop\Free_Novem_discord_bot> & C:/Users/willi/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/willi/Desktop/Free_Novem_discord_bot/bot.py
Traceback (most recent call last):
File "c:\Users\willi\Desktop\Free_Novem_discord_bot\bot.py", line 33, in <module>
print(input.setup)
^^^^^^^^^^^
AttributeError: 'builtin_function_or_method' object has no attribute 'setup'
PS C:\Users\willi\Desktop\Free_Novem_discord_bot>
I imported It
PS C:\Users\willi\Desktop\Free_Novem_discord_bot> & C:/Users/willi/AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/willi/Desktop/Free_Novem_discord_bot/bot.py
Traceback (most recent call last):
File "c:\Users\willi\Desktop\Free_Novem_discord_bot\bot.py", line 33, in <module>
print(cogs.input.setup)
^^^^^^^^^^^^^^^^
AttributeError: module 'cogs.input' has no attribute 'setup'
PS C:\Users\willi\Desktop\Free_Novem_discord_bot>
wha-
