#discord-bots
1 messages · Page 278 of 1
But the role wasn't cached so it returned None.
to get the discord.Role object
what
Get is for cached objects, where as fetch is for non cached objects, you will use the API to get the info.
But in this case you only need the .id attr so to fix this we simply make mod_role a snowflake.
overwrites ={
guild.default_role: discord.PermissionOverwrite(view_channel=False),
interaction.user: discord.PermissionOverwrite(view_channel=True),
discord.Object(config.mod_role): discord.PermissionOverwrite(view_channel=True)
}
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
ye
discord.Object worked
ty
@cloud dawn how do we send multiple embeds in one message?
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
multiple embeds
yeah
no i said embeds
OH
how simple is it to make a bot for message proxying? like similar to tupperbox and such
I'd say it's on the difficult side, definitely at least 2/3 years of programming experience if you code a lot.
is there a channel to show off my python discord bot?
Here, this is for any questions and discussions relating to Discord bot development.
Anyone figure out how to subclass pycord or fork discord.py to grab a speaking event?
wait I can send a video? 😄 I got excited to share when I made my voicechat bot faster
You can discuss the features of the bot, but do remember that we don't allow advertisement.
er, maybe I should send the github only
https://github.com/danomation/GPT-4-Discord-Voice project I've been working on. Trying to remove the dependency on node.js for the user's voice speaking event. Otherwise entirely python. I'm a noob in programming so code prob looks terrible
Code looks alright but I recommend not pushing any large commented out codes or a lot of comments in general in a final product.
I'll just make a flag for the user to enable the gpt functions like live weather and scraping. That way I don't have it all commented out. Plus I need to clean the code a bit more
I do like the concept, tough not sure why you have a js and a py bot.
It has to do with that speaking event. Python discord libraries lack the ability to check if a user is speaking. now py libraries can definitely send and record voice to a voice channel. Thats actually what I hope to get some traction on here. I'm sure I can subclass the discord gateway classes to get the user speaking status
I mean anything that you can do in js you can do in py.
Im sure you can do it but none of the libraries I've found can handle it out of the box
I could use a message trigger, but that removes a lot of the ease of access by immediately transcribing and responding by voice itself
Discord has a general speaking event, and it should have the currently speaking members, but Pycord doesn't directly expose any of this. Here there's a _hook that does nothing https://github.com/Pycord-Development/pycord/blob/master/discord/gateway.py#L857-L887
Some clever subclassing could do the job I think
I just haven't been able to get any opcodes
@frozen pivot they do have some issues open regarding it https://github.com/Rapptz/discord.py/pull/9288/commits
my current code uses pycord for the receiving audio and replying with audio . Just the speaking trigger is what I'm after. Best I can tell they haven't tackled that but I'm still looking through this
I'd just recommend building your idea in js then.
I'm working with a tutor to help me to do that. Though, I like python a lot 🙂
Thanks for you looking over this and doing some searching. I'll get there eventually
@frozen pivot Did some more digging and apparently why not many libs have it is because it can break very easily and is undocumented thus against ToS.
oof
Not the ToS part that is stopping them but the part that it is undocumented.
Yeah voice in general is poorly documented from what I've heard from pycord peeps
Well yeah since it's a bit of a grey area since there are a lot of things regarding voice and receiving that can break ToS or even laws for that matter.
It's a shame because it's a cool idea to speak back and forth. I want to make a project that also is an ai voice changer. For shy speakers with social anxiety they can use a surrogate to speak with the rest of the peeps
You could also make a bot sit in each general channel of a server and have conversations between guilds lmao
what does it do ? does it use like webhooks stuff to forward messages between servers?
Eula's can't cover ToS breaking
I hear ya
You either break it or you don't. However the chances of Discord actually enforcing it is fairly low.
I mean voice is pretty demanding if you could create an infrastructure that supports 100+ guilds with AI voice cover and GPT it would be very impressive and costly..
They would add their own API tokens
Not a chance in the world I can get this quality without a large gpu cluster
I suspect discord will create their own bot for this purpose in a year or so
clyde 2.0 coming soon
Now using a free tts could scale. gTTS sounds crap though
I already use it when I don't want to eat my paycheck away
is there any event on resume gateway connection that i can utilize?
What are you trying to do?
!d discord.on_resumed
discord.on_resumed()```
Called when the client has resumed a session.
resume or resumed? chat gpt said on resume xD
that gpt meme gets stuff wrong constantly 😦
Dont use gpt for coding 😵💫
It might seem cool but its more problem solving than just using google and docs
It's cool to generate ideas, or lead you to places, but not for straight coding
i mean its pretty handy, yeah but i just wanted to know if on reume event existed
in the first place
So why didnt you check docs?
That's the only place that will tell you
cause its faster just to type there cause the name could be diferent
Should import the entire docs into GPT and then ask 😄
or it can be done in other way
yea thats the best way to go i have to do it
not like you have all events list with categories

and since its a gateway event https://discordpy.readthedocs.io/en/stable/api.html#gateway
sure i prefer to just ask ; )
ask gpt -> check if answer works -> if not ask here or go to docs so you are most likely loosing time
btw on_resumed is weird, I mean why not on_resume
probably because the dapi docs call the event "Resumed"
does anyone know how to fix this error?
here's the code:
import discord
import os
import twitchio
from webserver import keep_alive
from twitchio.ext import commands
DISCORD_BOT_TOKEN = os.environ['TOKEN']
TWITCH_CLIENT_ID = os.environ['TWITCH_CLIENT_ID']
TWITCH_TOKEN = os.environ['TWITCH_OAUTH_TOKEN']
TWITCH_USERNAME = "graveyardztv"
discord_client = discord.Client(
intents=discord.Intents.all(),
command_prefix="!"
)
twitch_bot = commands.Bot(
token=TWITCH_TOKEN,
client_id=TWITCH_CLIENT_ID,
nick=TWITCH_USERNAME,
prefix='!',
initial_channels=[TWITCH_USERNAME]
)
@discord_client.event
async def on_ready():
print(f"We have logged in as {discord_client.user}")
await twitch_bot.start()
@twitch_bot.event
async def event_ready():
print(f"Twitch Bot Ready: {twitch_bot.nick}")
@twitch_bot.command(name='followers')
async def followers(ctx):
twitch_user = await twitch_bot.get_users(TWITCH_USERNAME)
if twitch_user:
followers_count = twitch_user[0].follows.total
await ctx.send(f"{Twitch_USERNAME} has {followers_count} Twitch followers!")
async def update_voice_channel_name(followers_count):
for guild in discord_client.guilds:
voice_channels = [channel for channel in guild.channels if isinstance(channel, discord.VoiceChannel)]
for voice_channel in voice_channels:
new_channel_name = f"{voice_channel.name} - Twitch Followers: {followers_count}"
await voice_channel.edit(name=new_channel_name)
keep_alive()
discord_client.run(DISCORD_BOT_TOKEN)
Either use Client or Bot, not both.
Well that's because this code is very old.
the commands.Bot is not a d.py's Bot
btw probably it's the twitch Bot object creation that's doing something to the event loop... check the docs maybe twitchio.ext.commands.Bot has a loop kwarg
and I don't think that you can run both of them in the same process but well, try it
whats old about it?
care to elaborate?
How do i download python on visual studios?
download vs code download pyton and add python to a path variable
variable path
I think you can just download vs code and python and after open a cmd and type python --version if it works then you can use it in vs code
@minor totem
Well you most likely copied this code.
no budy
i used documation @cloud dawn
script kiddie
can someone give me a good answer?
asyncio.ensure_future(obj, *, loop=None)```
Return:
• *obj* argument as is, if *obj* is a [`Future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future "asyncio.Future"), a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task"), or a Future-like object ([`isfuture()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.isfuture "asyncio.isfuture") is used for the test.)
• a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") object wrapping *obj*, if *obj* is a coroutine ([`iscoroutine()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.iscoroutine "asyncio.iscoroutine") is used for the test); in this case the coroutine will be scheduled by `ensure_future()`.
• a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") object that would await on *obj*, if *obj* is an awaitable ([`inspect.isawaitable()`](https://docs.python.org/3/library/inspect.html#inspect.isawaitable "inspect.isawaitable") is used for the test.)
If *obj* is neither of the above a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") is raised...
yep
Well is the obj passed a Future or a Task?
You need to create a loop using asyncio.new_event_loop() and pass it to everywhere
I mean class initializers and run methods
Probably would want to gather() them too
Generally I wouldn't recommend this approach, instead make two bots and setup communication between them
!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/RTMQ made some code to restart my fivem server, stop it, start it but it doesnt work, can anyone help?
is it possible after a .defer() to send a modal?
I know you have to use .followup or .edit_original_response but I was hoping there is a workaround that
anyone know why i cant use message.content on webhooks?
i don't believe so
Though you can follow up with a button or something that would open a modal
I know, thought of that. Just wish I'd save a step if possible. Thanks for the reply
No, it's returning the default avatar
I'm assuming you meant display avatar?
!d discord.Member.display_avatar
property display_avatar```
Returns the member’s display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
No i meant default
To separate user avatar and server avatar
What do you want to display on the embed?
It's working fine with display avatar (giving me server avatar) but doesn't returning me default avatar
Default avatar
The one i have right now
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
You need to handle when they don't have one set
Well i have one equipped but it still not showing
Oh wait
default_avatar doesn't work ig
It's returning avatar with member.avatar

!d discord.Member.default_avatar
property default_avatar```
Equivalent to [`User.default_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.default_avatar "discord.User.default_avatar")
Why put it there then if this doesn't work
it indeed works
i was making a discord bot with 3 python script files each having their own commands for a certain purpose but i ran into a problem where i try to run 1 of the commands in one of the scripts and it just gives me this discord.ext.commands.errors.CommandNotFound
It means that command file isn't loaded or u made some mistake in making the command due to which it isn't being recognized
how do i load it
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.
do i need to use cogs to load scripts into the main?
Yes
yo guys how I can make slash commands
And are slash commands same as application commands
with discord.py 2.0? see this brief explanation <#1125984891784400978 message>
some official examples of application commands:
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py#L47-L113
dpy documentation:
https://discordpy.readthedocs.io/en/stable/interactions/api.html#decorators
slash commands are a subset of application commands, the two other types that exist are message commands and user commands
https://discord.com/developers/docs/interactions/application-commands#user-commands
https://discord.com/developers/docs/interactions/application-commands#message-commands
Thanks bro
But in first link to a message it doesn't import app_commands like that in second example code from GitHub
Why
And Please tell what is use of bot.tree.sync
the first example doesnt import app_commands because it doesnt directly use it, on github it does in several places
and application commands must be registered directly with discord, otherwise your discord app wont show anything when you try looking for your command
Hmm
ah, well i don't have much experience with setting up communications between two different bots so i wouldn't know where to start
done that and got a new error
Send the new error then
You most likely will keep getting them as it's very problematic to run bots like this
i got this error then when i put the positional argument in it, it gives this second error
i'll send the updated code aswell
import discord
import os
import twitchio
import asyncio
from webserver import keep_alive
from twitchio.ext import commands
DISCORD_BOT_TOKEN = os.environ['TOKEN']
TWITCH_CLIENT_ID = os.environ['TWITCH_CLIENT_ID']
TWITCH_TOKEN = os.environ['TWITCH_OAUTH_TOKEN']
TWITCH_USERNAME = "graveyardztv"
discord_client = discord.Client(
intents=discord.Intents.all(),
command_prefix="!"
)
twitch_bot = commands.Bot(
token=TWITCH_TOKEN,
client_id=TWITCH_CLIENT_ID,
nick=TWITCH_USERNAME,
prefix='!',
initial_channels=[TWITCH_USERNAME]
)
twitchbot_event_loop = asyncio.new_event_loop()
@discord_client.event
async def on_ready():
print(f"We have logged in as {discord_client.user}")
await twitch_bot.start()
@twitch_bot.event
async def event_ready():
print(f"Twitch Bot Ready: {twitch_bot.nick}")
@twitch_bot.command(name='followers')
async def followers(ctx):
twitch_user = await twitch_bot.get_users(TWITCH_USERNAME)
if twitch_user:
followers_count = twitch_user[0].follows.total
await ctx.send(f"{Twitch_USERNAME} has {followers_count} Twitch followers!")
asyncio.set_event_loop(twitchbot_event_loop)
async def update_voice_channel_name(followers_count):
for guild in discord_client.guilds:
voice_channels = [channel for channel in guild.channels if isinstance(channel, discord.VoiceChannel)]
for voice_channel in voice_channels:
new_channel_name = f"{voice_channel.name} - Twitch Followers: {followers_count}"
await voice_channel.edit(name=new_channel_name)
twitchbot_event_loop.run_until_complete(update_voice_channel_name(followers_count))
keep_alive()
discord_client.run(DISCORD_BOT_TOKEN)
Hi there!
Q: is there any free services to run bot python to discord ?
Yes
if you'd like it running 24/7 i can tell you how to do that aswell
i don't think a bot can screenshot a website though i might be wrong
i can help you with the hosting of your bot
dm me
smh replit isn't good
bro is advertising replit
it's pretty decent for smaller bots that don't need a lot of resources
why'd you delete your messages?
because they weren't completely correct for his case
ah okay
just use selenium
what about shared ips and code?
is there a way to timeout people using discord.py?
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.11)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Lets say i want to timeout them for two hours, how do i do it
await ctx.author.timeout(2) ?
did you even open the docs page?
until (Optional[Union[datetime.timedelta, datetime.datetime]]) – If this is a datetime.timedelta then it represents the amount of time the member should be timed out for. If this is a datetime.datetime then it’s when the member’s timeout should expire. If None is passed then the timeout is removed. Note that the API only allows for timeouts up to 28 days.
it explains that clearly
Read that, understand and do it
i dont know how to work with datetime but alright i will read it
if you dont know how to work with datetime doesnt mean you can just pass random numbers and expect it to work
I didnt say it will work
@client.event
async def on_message(message:discord.Message):
if message.reference is not None:
replied_to:discord.Message = await message.channel.fetch_message(message.reference.message_id)
if replied_to.author.id in [823297858467397642]:
await message.author.timeout(datetime.timedelta(hours=2),reason="Replying to Staff")
i think this is correct
should be
also just a tip that literally changes nothing but makes you look cooler and profesional when you are dealing with static lists like here if ... in [823297858467397642] you should use tuples (value1, value2) instead
oh, nice tip thank you really appreciate it 😄
Also im getting this error idk why
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
self.run()
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\dns\win32util.py", line 48, in run
self.info.domain = _config_domain(interface.DNSDomain)
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\dns\win32util.py", line 26, in _config_domain
if domain.startswith('.'):
AttributeError: 'NoneType' object has no attribute 'startswith'
i have one task loop in my code is that causing this problem
well looks like domain is None
i have no variable named domain
import datetime
import discord
from colorama import Fore
from mcstatus import JavaServer
from discord.ext import commands,tasks
from config import TOKEN,GUILD_ID,SUGGESTION_CHANNEL_ID,BUG_REPORTS_CHANNEL_ID,SERVER_IP
global guild
client=discord.Bot(debug_guilds=[GUILD_ID],intents=discord.Intents.all())
@client.event
async def on_ready():
global guild
guild = client.get_guild(GUILD_ID)
print(f"Logged into discord")
change_status.start()
@client.event
async def on_message(message:discord.Message):
if message.reference is not None:
replied_to:discord.Message = await message.channel.fetch_message(message.reference.message_id)
if replied_to.author.id in (823297858467397642):
await message.author.timeout(datetime.timedelta(hours=2),reason="Replying to Staff")
if message.channel.id in [SUGGESTION_CHANNEL_ID,BUG_REPORTS_CHANNEL_ID]:
try:
await message.add_reaction("👍")
await message.add_reaction("👎")
except:
pass
@tasks.loop(seconds=10)
async def change_status():
try:
fserver = JavaServer.lookup(SERVER_IP)
fstatus = fserver.status()
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{fstatus.players.online} Players!'))
print(f"[Debug] Pinged! | Players : {fstatus.players.online}")
except Exception as ex:
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Server Offline!"))
if __name__ == "__main__":
client.run(TOKEN)
is this full traceback?
yes
There is a thread, that's the reason of cut traceback i guess
im using mctools module to get the number of players online in a minecraft server
I deleted this line and now it gives no error:
change_status.start()
well you are not starting the task now
but it shouldn't give anny error since the whole task loop is in a try except block
yea just wanted to check if thats the problem
thats not really a way to handle exceptions in tasks
there is another way?
you can check out this https://fallendeity.github.io/discord.py-masterclass/tasks/#reconnect-exceptions-handling but not sure if that applies here
A hands-on guide to Discord.py
!e
from threading import Thread
def f():
1 / 0
try:
t = Thread(target=f)
t.start()
t.join()
except:
print(123)
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Exception in thread Thread-1 (f):
002 | Traceback (most recent call last):
003 | File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
004 | self.run()
005 | File "/usr/local/lib/python3.11/threading.py", line 975, in run
006 | self._target(*self._args, **self._kwargs)
007 | File "/home/main.py", line 4, in f
008 | 1 / 0
009 | ~~^~~
010 | ZeroDivisionError: division by zero
oh
thats weird
that's actually
an insane amount of api calls
I mean those features do require those api calls
I have an issue with a command that works usually but doesnt work as a slash command. (1. The error -- 2. The code)
( 1 )
- Traceback (most recent call last):
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'addemoji' raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
( 2 )
@bot.tree.command(name="addemoji", description="Add an emoji")
@commands.has_permissions(manage_expressions=True)
@app_commands.describe(name = "name")
@app_commands.describe(source = "source")
async def addemoji(ctx: discord.Interaction, name: str, source: str):
try:
emoji = await ctx.guild.create_custom_emoji(name=name, image=source)
await ctx.response.send_message(f"Emoji '{name}' added: {emoji}")
except discord.Forbidden:
await ctx.response.send_message("I don't have permission to add emojis.")
except discord.HTTPException:
await ctx.response.send_message("Failed to add the emoji. Please make sure the URL is valid and the image is in the correct format.")
ImportError: cannot import name 'Enum' from 'discord' (unknown location)
as it tells you
you cant import Enum from discord
It's not in my code it's in module

you never showed full traceback
wavelink 🧐
all i can help you is check your libraries installed but i didnt tell you that 🤫
Hello, I recently started to code bots for more than one server at the time. I noticed that the same code is being executed for all the servers. Is there a way to create something like multiple instances for each server?
'datetime.timedelta' object has no attribute 'isoformat'
im getting this error
show full traceback not just message
but seems like you are trying to use isoformat method on it
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\imac\PycharmProjects\NeverLand\main.py", line 26, in on_message
await message.author.timeout(timedelta,reason="Replying to Staff")
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 854, in timeout
await self.edit(communication_disabled_until=until, reason=reason)
File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 823, in edit
] = communication_disabled_until.isoformat()
AttributeError: 'datetime.timedelta' object has no attribute 'isoformat'
@client.event
async def on_message(message:discord.Message):
if message.reference is not None:
replied_to:discord.Message = await message.channel.fetch_message(message.reference.message_id)
if replied_to.author.id in (823297858467397642,764417255018594314):
timedelta= datetime.timedelta(hours=2)
await message.author.timeout(timedelta,reason="Replying to Staff")
await message.channel.send(f"{message.author.name} به دلیل ریپلای به {replied_to.author.name} 2 ساعت تایم اوت
is this discord.py?
py-cord
ah then it explains it all
in pycord you cant use timedelta
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
it can be datetime.datetime only
but
there is other method that accepts timedelta
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
check out this method ^ @normal jasper
Thank you so much it works now
❤️
Hello, I would like to know how I can make that when the timer ends a message is sent to say that the vote is finished in my code below I have an error at the end of the timer which is :
2023-07-30 17:24:04 ERROR discord.ui.modal Ignoring exception in modal <my_modal timeout=None children=3>:
Traceback (most recent call last):
File "C:\Python311\Lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
await self.on_submit(interaction)
File "C:\Users\Shadow\Desktop\Discord Bot\Cutie\BFS - Blox Fruit Service\Test_bot\cogs\vote.py", line 73, in on_submit
await interaction.response.send_message(content="Voting has ended!", ephemeral=True)
File "C:\Python311\Lib\site-packages\discord\interactions.py", line 774, in send_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
Here is the code for my vote.py
Thanks in advance to those who will take the time to help me and I apologize in advance for the inconvenience.
U might be trying to respond to an interaction twice using interaction.response
Whereas it can only be used once
After that u have to use interaction.followup
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
Or the interaction has already completed
So the message that returns that "the vote is over" to do this I must do interaction.followup("the vote is over")?
interaction.followup.send(...)
Ohw .send okey I'll try that!
It works, thank you very much! But I have another question, if you don't mind?
Fire away
In my voting embed I have the % user reaction percentage for each possible answer. The problem is that it works every other time but I can't figure out why and I have no errors. 
Can u elaborate it I can't understand what u mean
This is the embed that my voting command returns when I click on a reaction it should update the % for example it should put me 100% for option 2 but it only works every other time.
You mean it doesn't show the percentage?
What every other time 
You mean the bot is not processing the reaction when it should?
exactly when I click on the reaction the percentage should increase but it doesn't all the time. Excuse me for my poor English, I don't speak basic English. 😅
Can you show the code responsible for handling it?
async def update_embed():
nonlocal timer, votes
total_votes = sum(votes.values())
updated_embed = discord.Embed(title=self.title, description=f'{self.texte}: \n\n{self.responses}', color=0x000cff)
updated_embed.set_thumbnail(url="https://media.discordapp.net/attachments/1130037768928628807/1130440607932874784/standard_1.gif")
updated_embed.set_footer(text=f"Voting time left: {timer}")
if self.responses.default is not None:
response_lines = self.responses.default.splitlines()
else:
response_lines = []
for reaction, count in votes.items():
percentage = count / total_votes * 100 if total_votes > 0 else 0
option_text = response_lines[int(reaction[0]) - 1] if response_lines else f"Option {reaction[0]}"
updated_embed.add_field(name=f"{reaction} {option_text}", value=f"{count} ({percentage:.2f}%)", inline=False)
await msg.edit(embed=updated_embed)```
Just this code, or did you want the entire file code?
import json
from discord import Webhook
import aiohttp
with open('config/config.json', 'r') as config_file:
tk = json.load(config_file)
webh = tk['webhook']
async def logged():
async with aiohttp.ClientSession()as f:
webhook = Webhook.from_url(url=webh, session=f)
await webhook.send('hello world')
idk why i just get this error "Command raised an exception: TypeError: from_url() got an unexpected keyword argument 'session'"
To access and modify timer and votes variables
Maybe the code that handles reactions being added is also useful
class my_modal(ui.Modal, title="Vote"):
texte = ui.TextInput(label="Texte", style=discord.TextStyle.short, required=True)
number = ui.TextInput(label="Number of responses", style=discord.TextStyle.short, required=True)
responses = ui.TextInput(label="responses", style=discord.TextStyle.paragraph, required=True, default="")
def __init__(self):
super().__init__()
self.vote_finished = False
async def on_submit(self, interaction: Interaction):
timer = 60
reactions = []
numbers = int(self.number.value)
for i in range(1, numbers + 1):
reactions.append(str(i) + "️⃣")
embed = discord.Embed(title=self.title, description=f'{self.texte}: \n\n{self.responses.default}', color=0x000cff)
embed.set_thumbnail(url="https://media.discordapp.net/attachments/1130037768928628807/1130440607932874784/standard_1.gif")
msg = await interaction.channel.send(embed=embed)
await interaction.response.send_message(content="Vote sent successfully", ephemeral=True)
for reaction in reactions:
await msg.add_reaction(reaction)
start_time = time.time()
votes = {reaction: 0 for reaction in reactions}
def check(interaction: Interaction, user: discord.User):
return interaction.user.id == user.id and time.time() - start_time < 60
async def update_embed():
nonlocal timer, votes
total_votes = sum(votes.values())
updated_embed = discord.Embed(title=self.title, description=f'{self.texte}: \n\n{self.responses}', color=0x000cff)
updated_embed.set_thumbnail(url="https://media.discordapp.net/attachments/1130037768928628807/1130440607932874784/standard_1.gif")
updated_embed.set_footer(text=f"Voting time left: {timer}")
if self.responses.default is not None:
response_lines = self.responses.default.splitlines()
else:
response_lines = []
for reaction, count in votes.items():
percentage = count / total_votes * 100 if total_votes > 0 else 0
option_text = response_lines[int(reaction[0]) - 1] if response_lines else f"Option {reaction[0]}"
updated_embed.add_field(name=f"{reaction} {option_text}", value=f"{count} ({percentage:.2f}%)", inline=False)
await msg.edit(embed=updated_embed)
while timer > 0 and not self.vote_finished:
await asyncio.sleep(1)
timer -= 1
await update_embed()
try:
reaction, user = await interaction.client.wait_for('reaction_add', timeout=0.5)
if reaction.emoji in reactions and check(interaction, user):
votes[reaction.emoji] += 1
except asyncio.TimeoutError:
pass
# Voting is finished, send the "Voting has ended!" message
if not self.vote_finished:
self.vote_finished = True
await interaction.followup.send(content="Voting has ended!")
await update_embed()
What library is the discord package you're using
!d discord.Webhook.from_url
classmethod from_url(url, *, session=..., client=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") from a webhook URL.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
Are you sure that it's really discord.py? Because I don't think so
yeah im pretty sure it is
its likely discord.py 1.7.3
https://discordpy.readthedocs.io/en/v1.7.3/api.html#discord.Webhook.from_url
from_url(url, *, adapter)
Is this a question for me?
no im sure it was for me
how do i update it
No
pip install --upgrade discord.py
oh okey !
!d discord.Reaction.emoji
The reaction emoji. May be a custom emoji, or a unicode emoji.
I think if you compare this to a string the results will always be False
I'd recommend you to convert it to a string before comparing
Should I convert reaction.emoji to string before comparing it to reactions and check(interaction, user)?
what are the standard practices that i should follow to make embeds on runtime??
This is a bit off topic but figured people here might know.
I want to make a bot for google chat. I have not tried anything yet but I see there is a chat api from google. Anyone have experience in this area that can recommend a direction ?
Hello, I recently started to code bots for more than one server at the time. I noticed that the same code is being executed for all the servers. Is there a way to create something like multiple instances for each server?
I could create them manually but is there a procedure that I should follow?
You can use a database so that the bot may be configured on a per-server basis, but you don't need to be running an instance of the bot for each individual server
guys
I really need help with something
please refer to #1035199133436354600
@gloomy hound (it does say ping to reply)
thanks I appreciate it :D
:incoming_envelope: :ok_hand: applied timeout to @gilded depot until <t:1690737144:f> (10 minutes) (reason: mentions spam - sent 7 mentions).
The <@&831776746206265384> have been alerted for review.
him
jesus christ
Wat
blocked dc
ill explain: please refer to the #1035199133436354600
if u gave me and the cooldown a chnace maybe you would have seen why......
or imma just leave this server
@odd minnow you got muted by the bot for a reason, jumping onto a second account to evade it really isn't what you should've done
meh
ive been tackling this piece of code for days which ironically enough is a discord bot
so Im not gonna let something which is similar to what im making stop me
from helping its own kind
the guy just wrote the channel name in all channels
totally normal you dont do that stuff?
ye, twice a week
how I can make it work after the reset?
@client.command()
async def suggest(ctx, *, reason):
count1 = 0
count2 = 0
interacted_users = []
async def button_callback1(interaction):
nonlocal count1
user_id = interaction.user.id
if user_id not in interacted_users:
count1 += 1
interacted_users.append(user_id)
print(f"Good Suggestion Count: {count1}")
embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")
await interaction.message.edit(embed=embed)
await interaction.response.send_message("Thank you for your vote!", ephemeral=True)
else:
await interaction.response.send_message("You have already voted.",ephemeral=True)
async def button_callback2(interaction):
nonlocal count2
user_id = interaction.user.id
if user_id not in interacted_users:
count2 += 1
interacted_users.append(user_id)
print(f"Bad Suggestion Count: {count2}")
embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")
await interaction.message.edit(embed=embed)
await interaction.response.send_message("Thank you for your vote!", ephemeral=True)
else:
await interaction.response.send_message("You have already voted.",ephemeral=True)
button = discord.ui.Button(style=discord.ButtonStyle.green, label="Good Suggestion", custom_id="Good_Suggestion")
button.callback = button_callback1
button2 = discord.ui.Button(style=discord.ButtonStyle.red, label="Bad Suggestion", custom_id="Bad_Suggestion")
button2.callback = button_callback2
embed = discord.Embed(color=ctx.message.author.color, timestamp=ctx.message.created_at)
embed.set_author(name=f"{ctx.message.author}({ctx.message.author.id})", icon_url=ctx.message.author.avatar)
embed.add_field(name='Suggestion:', value=f"{reason}")
embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")
view = discord.ui.View()
view.add_item(button)
view.add_item(button2)
message = await ctx.send(embed=embed, view=view)
embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")
await message.edit(embed=embed)
do you mean you want the buttons work after reset?
yes
Store the data in database and load from it instead of memory
And make them persistent after that
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
exaple how to do that ^
you need to register persistent view exaple above explains it
ok
https://pastebin.com/i58ugAJn
I have this piece of code
that when I cicktthe bttton
it disables the usesrs permissions
apart from the random users
This doesnt work tho
insteas
everyond send permissions remain as true
please help
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hey I have a really dumb question. I am trying to find a good way to do speech recognition in real time in a discord voice channel. I am having trouble though and was wondering if any one has a code snippet or something like that to point me in the right direction
The problem is not even all libraries support voice receiving
Iirc nextcord does tho
Nextcord?
I’ll do some research on it and see if I can find some good stuff with it. Just a google and this looks great. Ty man
Dpy fork
That's a rare topic to see here, good luck with that, seems interesting
Ty man. Is it ok if I dm for any questions. Trying to make something fun for some friends and possible YouTube video. But i want to spend some hours messing with it before i ask any dumb questions
Im sorry but what the actualfuck - bruh answer my question please
what a great way to make people want to help you
Both do, lol.
does nextcord actually implement it? last i checked i couldnt find any mention of it in their docs
also the issue for it seems to be open: nextcord/nextcord#54
i want to add tries to this command
@bot.command()
async def play(ctx, n):
tries = 0
number = str(random.randint(1,int(n)))
await ctx.send(f"guess the number between 1 and {n}")
def check(msg=discord.Message) -> True:
return msg.content == number and tries == 5
try:
p = await bot.wait_for('message', check=check)
if p.content == number:
await ctx.send(f"you win the number was {number}")
else:
tries += 1
except asyncio.TimeoutError:
await ctx.send(f"time over the number was {number} and you did x tries")```
any ideas?
use it with a while loop
You can loop while guess != number
can i give it a try and show it and you can tell me what i did wrong
try it if you want
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = '.', intents=intents, help_command=None)
prefix = '.'
class Bot(BotBase):
async def process_commands(self,origin):
ctx = await self.get_context(origin, cls=Context)
if ctx.command is not None:
await self.invoke(ctx)
async def on_message(self, message):
await self.process_commands(message)
bot = Bot()
ctx.command returns None, so commands for my discord bot don't get processed- any ideas on why this might be happening?
can someone help here #1135433078886645882
Have you enabled message content intents?
^ didnt think of that but good point
though why are you inheriting BotBase instead of commands.Bot? you're missing a lot of Client functionality with it
Using the discord API, what would be the best way to query my discord server to get how many are in my server?
probably GET /guilds/{guild.id}?with_counts=true, retrieving the approximate_member_count field
https://discord.com/developers/docs/resources/guild#get-guild
this is old code I wrote a few years back
should I switch to commands.Bot?
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
yes in my code too
^^
at the top
ah didnt see that mb
What's the reason to override process_commands?
Hmm, but actually the source code has kinda the same thing
Maybe something wrong with your context class?
hmm good thinking
so my code is ran through cogs
by context class do you mean classes I have under cogs?
ohhh
I can delete it but that's the default parameter for cls
it's not a custom context class
Hmm, didn't you get an error in this code? I guess i see the problem, but you should get an error with that
Ahh, understood
There is no error because BotBase is subclassed, not client or bot
I didn't get any errors
wdym by this?
Someone can help in #1135451461753503815
ty i'll give this a crack
you pass the intents to the commands.Bot instance
not to your own Bot instance
and then you end up overriding the commands.Bot instance anyways so it is never used
hey guys
i think imma getting trashed but please how can i create a discord bot with each command in a single file and execute them all with a main ?
Trying to write a command that will return an image of fox from some-random-api and found this piece of code online, but for some reason it doesn't work.
The console points at line 34, but i dont see anything wrong there
feel free to ping me, though
!e
import json
json.loads("")
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | json.loads("")
004 | File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
005 | return _default_decoder.decode(s)
006 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
007 | File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
008 | obj, end = self.raw_decode(s, idx=_w(s, 0).end())
009 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
010 | File "/usr/local/lib/python3.11/json/decoder.py", line 355, in raw_decode
011 | raise JSONDecodeError("Expecting value", s, err.value) from None
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/L5XUFJJ6FOUXTIKGHWZLNOXTMA
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!
Guys
I really need help with something
and I apologise for the disrespect
but I really would appreciate help 🙂
https://pastebin.com/i58ugAJn
I have this piece of code
that when I cicktthe bttton
it disables the usesrs permissions
apart from the random users
This doesnt work tho
insteas
everyond send permissions remain as true
please help
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
hey guys
i think imma getting trashed but please how can i create a discord bot with each command in a single file and execute them all with a main ?
If you know u are getting json then u can directly use .json() method
see about commands.Cog
is there a way to check if a specific command has been synced with a server?
bot.tree.sync() return list of all the synced commands @grim robin
i think i made some progress, but this happens:
Open the developer tools inside Discord then make a request to Discord while you have the network tab open look where it sends a request when it sends an interaction and recreate that request with a non existing slash command that will eventually exists.
i think i need to somehow specify that i need the "image" from here
but it also actively tries to sync commands. I don't want to sync them, I just want to check if a specific one is already synced
Print response.json() and see what it's returning
@grim robin Do know that this is a bit of a "grey" area meaning it isn't "really" against ToS but isn't a supported method of doing it. Meaning Discord likely doesn't want you to.
But then again, Discord could've added a simple event imo
Yeah it's dictionary. Do you know how to access any value with key?
!d dict.get
get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
actually, no. I'm still new to python and only know basic syntax 🙂
oh u can access the value of any dictonary like this
a = {
"name": "Mannu",
"age": 16
}
name = a["name"]
age = a["age"]
print(f"{name} is {age} yo, good boy.")```
can I see the code
resp = requests.get('https://some-random-api.ml/img/fox')
data = resp.json()
imageurl = data["image"]
embed1 = discord.Embed(color=0xff9900, title='Random Fox')
oh, ignore the embed thingy
it should work
so i tried adding chatgpt to my dc bot but when i try to execute the command it tellss me i didnt provide an api key even though i did. can someone tell me what i did wrong?
wait lemme check
there should be a space b/w Bearer and api key
damn im stupid
its returning html
and i need that thing to return me json, right? idk why it doesn't work tho
hmm
the full command code, though i dont think it will make any difference
@client.command()
async def fox(ctx):
resp = requests.get('https://some-random-api.ml/img/fox')
data = resp.json()
imageurl = data["image"]
embed1 = discord.Embed(color=0xff9900, title='Random Fox')
embed1.set_image(text=imageurl)
await ctx.send(embed=embed1)
I recommend using get.
use this url
he is new to python
well many ways to do same work
yup, this one works, while the other one doesn't. broken api ig?
yep
enjoyyy
Is there any advantage besides ability to set default value not to cause KeyError
Well then you should handle the Keyerror.
As long as you ensure that the running program won't crash/stop.
Ik you're a beginner but using sync lib in async app is problematic, use aiohttp instead of requests
async with aiohttp.ClientSession() as session:
r = await session.get('...')
data = await r.json()
Thanks! I will try that next time
You forgot the space between Bearer and token itself I think
yeah ik, im stupid

hi guys i need to set embed footer with interaction.user.joined_at , what should i write after interaction.user.joined_at
You sure you need footer and not timestamp
oh
Timestamp is set in constructor
embed = discord.Embed(timestamp=interaction.user.joined_at)
There probably is a method but I forgor
Okay there's no
Only attr setting or constructor
yeah ty it works
Sounds to me like you're on a laptop.
Yes
And that you are using the trackpad.
something wrong with the discord? my bot are just sending the same message twice
Your bot running twice?
Check task manager to be certain.
Are you precessing commands inside a listener?
looks like i was stopping and starting the bot so fast that it make this thing happen
https://pastebin.com/i58ugAJn
I have this piece of code,
that when I cickt the bttton
it disables the usesrs' permissions to send messages (settint them as FALSE)
apart from the random users, as in...
please help here
Magik
please man
I actually really need help
2 days since i first started asking
i acc need help
please send your code and traceback
thats the prroblem
there is no error.
it just doesnt workin the way I inntended t to
ok, then send your code and explain what's going wrong
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
basically
# Randomly choose a member from all_members list
random_member = random.choice(all_members)
# Create a dictionary to store permissions for all members
member_permissions = {}
for member in channel.members:
if member == random_member:
# Random member has send_messages permission
member_permissions[member] = discord.PermissionOverwrite(read_messages=True, send_messages=True)
else:
# All other members have send_messages permission disabled
member_permissions[member] = discord.PermissionOverwrite(read_messages=True, send_messages=False)
this main bit is causing errors
You just said there is no error
When I click the buttton, it should get a random memebr from the list i made of all the members in the command the user would send, and then set everyone but that random members permissions to send messages as FALSE. so the random memnber should still have their perms to send messages as TRUE. When I run it tho and click the button, it does not do this, everyones perms remain as true.
tru mb i meant problems as i said there werent any errors
for team1_member in team1:
await channel.set_permissions(team1_member, read_messages=True, send_messages=True)
for team2_member in team2:
await channel.set_permissions(team2_member, read_messages=True, send_messages=True)
``` why are you enabling the permissions if you're going to disable them anyways
thats for when the v=channel is first created
after which the discord bot sends a button
when its clicked, that wehn I want it to disable perms
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
The overwrites argument, you can set permission overwrites immediately after creating the channel
ok
so ut saying I can pass this within my parentheses for the creat channel bit?
and this should help?
About making unnecessary requests, yes
?
but thanks @naive briar updating my code now, should this disable the user's perms when I click the button?
wait
bruh
I wrote overwrite instead of overwrites:
await channel.set_permissions(member, overwrite=discord.PermissionOverwrite(send_messages=False))
oops
maybe not
Hi, I was wondering, would you use inherited class for cogs :
from discord.ext import commands
class MyCog(commands.Cog):
def __init__(self):
super().__init__()
@commands.slash_command()
async def foo(self):
print("foo")
or just a cog instance ?
from discord.ext import commands
myCog = commands.Cog()
@myCog.slash_command()
async def foo():
print("foo")
There are maybe mistakes in the second version cuz I never used it
A cog subclass
!d discord.ext.commands.Cog.slash_command
No documentation found for the requested symbol.
Less messy
I asked ChatGPT he said same as u but cuz it was better to access bot class
And the second one isn't even valid
what's wrong ?
that's why I wrote something at the end of the message...
The first also isn't valid 
oh ye forgot self
Why would there be a slash_command decorator in the discord.ext.commands module
idk tbh I don't really understand decorators
and there is one
cuz I use this syntax for my bot
There is what
decorator
Where is it then
for slash_command in discord.ext.commands
@commands.slash_command(name="ask", description="Ask anything to ChatGPT!")
Actually working code ^
I doubt if commands is discord.ext.commands
If whatever library you are using actually has it, then it got a weird implementation
from the same script^
pycord
what should I use
I started discord.py
then saw it was deprecated
The discord.ext.commands is originally made for developers to make prefix commands easily
So I saw pycord
That's like 2 years ago
Pycord isn't mantained anymore?
wait why are there like 100+ packages for discord ??
pycord, nextcord, discord.py, discord componments
Its last update is a week ago
;-;
There are only Like 6 that are mantained
and which one is better ? :p
Which most of them are forks of discord.py
so not really useful right ?
Well for beginner i would suggest discod.py or nextcord
I'm not begginer with python but I'm new to discord
But discord.py is more used hence more examples online
decorators are likely one of the only things I don't get at all
That's what i meant by beginner
Well each of them got it
If you come from pycord i suggest nextcord
Its more Like pycord than discord.py
They are just functions that extend the behaviour of the functions that they are applied to
!e
def do_twice(func):
def predicate():
func()
func()
return predicate
@do_twice
def do_thing():
print('Hello!')
do_thing()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello!
002 | Hello!
In the case of something like @bot.command it's just taking your function, converting it into a Command object and registering it with your bot
How to fix?
File "C:\Users\KokoG\PycharmProjects\Discord Bots\D-SERV PAYMENTS\payments.py", line 90, in <module>
class PayPal(discord.ui.View):
File "C:\Users\KokoG\PycharmProjects\Discord Bots\D-SERV PAYMENTS\payments.py", line 99, in PayPal
@discord.ui.button(label='Link',style=discord.ButtonStyle.link, url='https://www.paypal.me/dservgaming', emoji='')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: button() got an unexpected keyword argument 'url'```
@slate swan
read the error
What should I replace it with ?
Buttons with a URL cannot be created with this function. Consider creating a Button manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
In other words, create the button manually and not in the decorator
guys, i have a command like
@bot.hybrid_command(name="test", with_app_command=True, description="test")
async def test(ctx):
x = 5
while x < 10:
if x > 10:
print('thats just a example')
break
my question is: when the user type the /test command twice can i break the while of a previous command? i know how to break it with a timeout, but i want know if it is possible for when the user type the command again it instantly break the while of previous command
What should I read to learn discord.py
read about event loops https://docs.python.org/3/library/asyncio-eventloop.html
How do I delete the last 2 messages?
hey please how can i create a channel in a specific place in a category with create_text_channel() method or else ?
!d discord.TextChannel.delete_messages
await delete_messages(messages, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes a list of messages. This is similar to [`Message.delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.delete "discord.Message.delete") except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this...
?
docs 💀
!d discord.CategoryChannel.create_text_channel
await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
thanks
bro can someone help me im about to ropemax
i coded this command for so long and its been working randomly i add some code to add a button to the embed
and then my command disappears
then i reload the cog
and resync it, then it comes back
but now the option is gone
like the command was /whois user:
now user disappeared
so its just /whois
BRO IM LITERALLY GONNA *FF myself anyone know the problem
i hate slash commands
im not about to scrap EVERYTHING ive just worked on bruh
ichanged my bot token i tried a different server i tried a different account with a different bot token nothing works
i deleted the cog and put the code in a different cog, idont think the problem is the code or my ide i think its discord but IDK HOW TO FIX IT
Posting the code itself tends to help us help you
why would i post my code just for someone else to use it?
my code isnt the problem
actually yeah one sec
opps
lemme grab code block
@commands.cooldown(1, 3, commands.BucketType.user)
async def user(self, interaction: discord.Interaction):
# Get the entered username from the user
username = interaction.data["options"][0]["value"]```
this is practically the only relevant thing
do u know the problem?
dang im stranded
with no help great
!d options
im ropemaxxing
How are you loading the cog and how are you syncing your commands
jishaku
Or whatever it’s called
It’s been working for a while
I've never used that nor really know what it is so I probably can't help
That's library containing connectable universal devonly cog with commands like exec, I dunno much tho
It's for people who can't code exec command by themselves
A discord.py extension including useful tools for bot development and debugging.
I think it’s more for people who don’t want to waste time
plus I recoded most of it by myself
slash command parameters are based on the signature of your function, but you dont have any user parameter written in there for discord.py to tell discord about...
have you been manually registering the command options with discord's API this whole time?
that use of interaction.data is very hacky too
how do I add users to a guild using the guild join scope?
I tried following the docs but it was too hard to understand and it didn't work for me
The guild join scope is not applicable in discord bot
Its for discord apps and you need redirect URL for that
And a running server that handles the requests
hm
nope
/whois user:
thats how it looked like with the code
it just popped up
and it got the information and everything
and it was working perfectly fine
seems like you had it correct at one point but you removed the user parameter and only recently synced the command, which made it disappear
do u know how i could correct it
from discord import app_commands
from discord.ext import commands
from discord.ui import View, Select
import requests```
these are my libs
maybe idk i had old versions of the code saved
add your user parameter back and use that in your command instead of interaction.data, e.g. py @app_commands.command() async def my_command(self, interaction, user: discord.Member): ... # ^^^^^^^^^^^^^^^^^^^^ also sync your command afterwards
and when i tried them nothing camp up
its not a discord member
its a user
like for another platform
for roblox
oh yeah
so my code grabs that does alot of api stuff and puts info out
typehint it whatever you want it to be
yes
the user can type in what they want
and then i recieve it
with interaction.data take it find the user grab the id them use the id for other apis to grab info about the user then display it
i meant type hint it as whatever type that you want the user to write in, a string, integer, whatever
im pretty new to discord.py so do u know how that would be done?
^
like what I can edit, and im still confused how it just disappeared
yes but discord.member
means mentioning a member if im correct
but the user just needs to type the name out
see also the example on the github repository
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
thanks
but im still confused, how would i make it so the user can type just letters
and numbers in the box
like how it was before i dont think im understanding
because i checked the first version of my code and i used the same method for this specific cog
and its being loaded properly and everything and synced
so im confused
you typehint it as a string type, str
ty so much
it worked and my code works again idk even know how it worked before
and now i dont need to use the work around
to grab the info
discord has its own version of the command structure that you first synced, meaning you can change or get rid of it and the slash command will still exist until you sync again
the weird thing is ive been constantly syncing
and editing the code and its been working. until i added something then my orginal method just completely crashed
although its fixed now so thank you so much
i almost had to scrap the code
hey please is there a selector for guild roles in a slash command like discord.Option(discord.Member) ?
yes you just annotate it as discord.Role
oh ok thanks
Please what this error means ?
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 7: Application command names must be unique
You've probably tried to register multiple slash commands with the same name
discord.ext.commands.errors.ExtensionFailed: Extension 'lib.commands.general' raised an error: TypeError: object NoneType can't be used in 'await' expression
I get this error when trying to load extensions for discord.py, I've attached my file tree- any ideas on what I did wrong?
looks like general.py is throwing an error when being loaded, you'll have to show the code you have inside the file
hey i was wondering, i know that some bots display the user list when trying to a autocomplete an object (in interactions)
like this
how can i do the same thing?
No clue why I keep getting this error in my code:
2023-08-01 02:39:33 ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "warn" is not found
The command itself:
@client.command()
async def vwarn(ctx, user: discord.Member, *, reason: str):
await log_command(ctx, "warn", f"{user.mention} - {reason}")
embed = discord.Embed(title="You've been warned!", color=discord.Color.orange())
embed.add_field(name="Moderator", value=ctx.author.mention, inline=False)
embed.add_field(name="Reason", value=reason, inline=False)
await user.send(embed=embed)
did you enable message_content intent?
annotate argument as discord.Member
certain commands work
import discord
import asyncio
from discord.ext import commands, tasks
from discord.utils import utcnow
client = commands.Bot(command_prefix="v", intents=discord.Intents.all())
guild_id = 1135722213287395338
community_member = 1135725714675601489
moderator = 1135725652054646824
senior = 1135725549961097367
logs = 1135723280997822605
moderator_role = None
senior_role = None
mod_logs_channel = None
@client.event
async def on_ready():
global moderator_role, senior_role, mod_logs_channel
print("\x1b[38;5;41m[SUCCESS] Bot Online")
guild = client.get_guild(guild_id)
moderator_role = discord.utils.get(guild.roles, id=moderator)
senior_role = discord.utils.get(guild.roles, id=senior)
mod_logs_channel = client.get_channel(logs)
await update_activity_loop()
async def update_activity_loop():
while True:
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Victoria County Staff"))
await asyncio.sleep(10)
total_users = sum(len(guild.members) for guild in client.guilds)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{total_users} users!"))
await asyncio.sleep(10)
async def log_command(ctx, action, arguments):
embed = discord.Embed(title="Command Log", color=discord.Color.orange())
embed.add_field(name="Moderator", value=ctx.author.mention, inline=False)
embed.add_field(name="Action", value=action, inline=False)
embed.add_field(name="Arguments", value=arguments if arguments else "N/A", inline=False)
await mod_logs_channel.send(embed=embed)
@client.command()
async def ping(ctx):
timestamp = utcnow()
embed = discord.Embed(title="Pong!", color=discord.Color.orange())
message = await ctx.send(embed=embed)
latency = (utcnow() - timestamp).total_seconds() * 1000
embed.add_field(name="Latency", value=f"{latency}ms", inline=False)
await message.edit(embed=embed)
await log_command(ctx, "ping", None)
@client.command()
async def vmodlogs(ctx, user: discord.User):
await ctx.send(f"Modlogs for {user.mention}")
@client.command()
async def vwarn(ctx, user: discord.Member, *, reason: str):
await log_command(ctx, "warn", f"{user.mention} - {reason}")
embed = discord.Embed(title="You've been warned!", color=discord.Color.orange())
embed.add_field(name="Moderator", value=ctx.author.mention, inline=False)
embed.add_field(name="Reason", value=reason, inline=False)
await user.send(embed=embed)
client.remove_command('help')
client.run("token")
@slate swan full code i guess
it literally tells you what to do?
TypeError: parameter 'interaction' is missing a type annotation in callback 'intercambio'
i dont know what to add though- Im a really slow learner
do you know what my issue is?
do you have any on_message event?
yeah the prefix is "v" and earlier putting the v there somehow fixed it
you need to annotate the interaction argument
let me try it without
like you did with others
now interaction is of type discord.Interaction
!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.
Typo
so interaction: discord.Interaction
try and see
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
is this command within a class?
What's interactions.Interaction?
if you mean a cog? yes.
its fine
may i see
what do you want to see exactly?
The cog
discord/interactions.py line 93
class Interaction(Generic[ClientT]):```
its just inside interactions file hence python shows it as this
I see
https://paste.pythondiscord.com/4RRQ Just the begining because i dont think anything after that is relevant?
you see this command is not inside a class
class X:
...
# this is inside class
...
# this is not
And doesn't interaction come before button arg in buttons?
in discord.py, yes
Then why he/she using it the other way

Cuz i think they are using dpy from discord.app_commands
yes its discord.py
tried to follow documentation, but turns out having adhd and english not being my first language is something that helps in that regard-
!d discord.ui.button @stone gate example can be found here
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
They do
Here 
examples/views/confirm.py lines 29 to 30
@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):```
@discord.ui.select(*, cls=discord.ui.select.Select[+ V], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.
To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
Welp docs of dpy have few examples in there docs
no you have arguments swapped
could you elaborate? sorry
Check your function in the buttons and the example above

https://paste.pythondiscord.com/CZSA back again, i dont know what happened but now commands arent recognised at all. It seems to be the Button class, if i remove it, the commands are read just fine?
https://paste.pythondiscord.com/PQJA this is the error i get as soon as i try to use a command, it says tag but its any under the cog
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
Can you show us where the tag command is defined?
https://paste.pythondiscord.com/5D2A just a few commands below
Mind pasting the whole file so we get the context?

https://paste.pythondiscord.com/3XUQ dont mind my weird jump between spanish and english, and some inconsistencies, its either my brain turning off or help from a friend, or some times a little bit of AI help
also its rough because i had to move a good chunk of the database from a trashy sql service that crashed every 5 requests to google sheets
Im having trouble listing commands using cogs and app_commands. Ive tried get_app_commands with examples online but no success yet
What's the problem
Ah, all of your commands are inside the view rather than the cog
You're using Google sheets as a database?
i dont know how to implement that into the code, was imagining something similar
@app_commands.command(name="help", description="help msg")
async def help(self, interaction: discord.Interaction):
commands = (self.get_app_commands())
for command in commands
print(command)
- TypeError: 'trainer' object is not iterable
yeah, i would usually use something else, but this specific use-case kinda requires it, it allows me to visualize and easily edit/data (and also i just like working with google sheets

and how can i solve that? its the first time im using the view thing
By moving the app commands into the cog rather than the view
Might be easier to move the view somewhere else instead
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
like where?;;;
- ERROR discord.app_commands.tree Ignoring exception in command 'help'
Traceback (most recent call last):
File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\cogs\shop\trainer.py", line 1397, in help
for command in self:
TypeError: 'trainer' object is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: TypeError: 'trainer' object is not iterable
even before imports?
for command in self 
And wait a minute, at line 1397!?
no
Basically what your issue is you have a class (cog) and it's broken up by the view in the middle
So everything after the view is considered to be part of the view because of python indents
oh, i see
Methods are methods of classes that are closest above it, so if you trace your tag command, you will see the closest class above it is the view
yes
self.get_app_commands()
for command in self:
print(command)
I still get the same error
and if I try to print it out right i get [<discord.app_commands.commands.Command object at 0x0000019C80B1CDF0>, <discord.app_commands.commands.Command object at 0x0000019C80B1CE20>, <discord.app_commands.commands.Command object at 0x0000019C80B1CE50>]
No, it's the for command in self that is causing the error
do u know a fix?
Don't do it?
Can you tell us what you're trying to do? We may be able to provide a better solution
It looks like you want to print all the app commands?
yes print all the commands listed in the bot
or at least that cog
You would loop over self.get_app_commands() then
i think it working:
for commands in self.bot.commands:
print(commands)
its app commands
The code they sent was already correct, how come it turns into for command in self
Technically it will but not sure it does what OP wants

i felt like it was correct but im getting an error that says its not iterable
I don't know about you, but a list is sure iterable
The thing that is not iterable is your cog, that you're trying to iter for some reason
Can you show us what you've got?
Im trying to list the commands, i figured since there was a specific code called get_app_commands that I could get them with it and list them
Can you paste the exact traceback too?
commands = self.get_app_commands()
for command in commands:
print(command)
right now what im getting is
<discord.app_commands.commands.Command object at 0x0000020D4FD1CEB0>
<discord.app_commands.commands.Command object at 0x0000020D4FD1CEE0>
<discord.app_commands.commands.Command object at 0x0000020D4FD1CF10>
Seems fine to me ☕
it was, I just had to add the qualified_name property to convert it
What
commands = self.get_app_commands()
for command in commands:
print(command.qualified_name)
it converts the <discord.app_commands.commands.Command object at 0x000001AA6801CE20> to the name of the command
i want to edit the perms of a user or a role so that they can not use slash commands.... how do i do that?
right now i am stopping them from sending a message in the channel:
https://srcb.in/eyd4JQSGiY
but is there a way to jus stop themfrom using the slash cmds only?
!d discord.Permissions.use_application_commands is probably what you want
Returns True if a user can use slash commands.
New in version 1.7.
thank you very much!
bot = TestBot(command_prefix="$", intents=intents)
logger = logging.FileHandler(filename="logs/discord.log", encoding="utf-8", mode="w+")
bot.run(KEY, log_handler=logger)
I have done basic logging setup.
_log = logging.getLogger(__name__)
is this the correct way to access logger in cogs??
it is how you should get the logger, however by default discord.py only sets up logging for itself, so your cog logger won't be writing to the same handler - if you want your cog (and all of your libraries) to share the same handler, you should use the root_logger=True argument in bot.run()
alr, thanks
would anyone know why when I do cntrl^c on my bot it takes forever to actually end the program
because the library is finishing and cancelling the tasks before completely shutting down the Bot
hmm.. really slows down development when I gotta wait to restart the bot. i know about cogs, but not everything is in a cog, so I need to restart the bot sometimes
some libraries (like disnake) supports cogs reloading when the files where they're in were edited
in that case you wouldn't need to restart the Bot
but the code im editing is not in a cog
is it in an extension?
no
no
Have you tried using the close method? Also, you could use importlib to programmatically re-import modules where needed
you can use importlib.reload to reload a module, but that's tricky to do
Just ask your question
hey can anyone help me with my error
btw i am new to python to please dont judgee me😅
Check line 11
Error is Preety descriptive
don't ask to ask, just ask
Just create a script.bat file and close the terminal instead of ctrl c then run that script file
Lol
I was wondering if I do something like this :
import discord
class Bot(discord.ext.commands.Bot):
def __init__(self):
super().__init__()
async def on_member_join(self, member: discord.Member):
print(member.name, "joined")
How can I add the event decorator within the class ?
cuz currently the on_member_join will not be called
It will
oh
The .event decorator just set the attribute to your callback function
What happened then
nothing...
Show your full code
from discord.ext import commands
import discord
import cogs
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
super().__init__(command_prefix="/", intents=intents)
self.add_cog(cog=cogs.Greetings(self))
self.add_cog(cog=cogs.Bot(self))
self.add_cog(cog=cogs.ApiRequests(self))
self.add_cog(cog=cogs.LocalGames(self))
async def on_ready(self):
print(f"Successfully logged in as {self.user.name}")
async def on_disconnect(self):
print(f"Disconnected from {self.user.name}")
the thing is in the greetings
import discord
from discord.ext import commands
import embeds
WELCOME_CHANNEL_ID = 1127663724635889818
class Greetings(commands.Cog):
def __init__(self, bot: commands.Bot):
super().__init__()
self.bot = bot
async def on_member_join(self, member: discord.Member):
welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
welcome_channel.send(embed=embeds.Welcome(member))
async def on_member_remove(self, member: discord.Member):
welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
welcome_channel.send(embed=embeds.Goodbye(member))
You need to declare them as listeners by using discord.ext.commands.Cog.listen
how
It's not the same thing as events
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
It's a decorator
like this ?
import discord
from discord.ext import commands
import embeds
WELCOME_CHANNEL_ID = 1127663724635889818
class Greetings(commands.Cog):
def __init__(self, bot: commands.Bot):
super().__init__()
self.bot = bot
@commands.Cog.listen("on_member_join")
async def on_member_join(self, member: discord.Member):
welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
welcome_channel.send(embed=embeds.Welcome(member))
@commands.Cog.listen("on_member_remove")
async def on_member_remove(self, member: discord.Member):
welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
welcome_channel.send(embed=embeds.Goodbye(member))
Mistyped it, listener not listen
listen doesn't exist
Could you just join my test server and leave it just to see if it works please ?
No
Me when people are too lazy to create a secondary account to test anything they want
true
i m trying to make the bot play a music using ffmpeg it works fine when i going to play another song he doesn't and thats because theres error in the package i don't what this what vs code show me :
Traceback (most recent call last):
File "C:\Users\Nassim\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Nassim\Desktop\dogs\main.py", line 34, in on_message
voice_p = await voice_channel.disconnect()
^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'voice_channel' where it is not associated with a value
await voice_channel
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 7, in <module>
003 | a()
004 | File "/home/main.py", line 3, in a
005 | b + 1
006 | ^
007 | UnboundLocalError: cannot access local variable 'b' where it is not associated with a value
stupid question : Are alt allowed on discord or I have to use a name that is not recognizable ?
Why wouldn't it be?
idk since bot could create tons of alt to spam users
Unless you'd use it for to bypass bans
ok ty
Spamming is not allowed in the first place
ye true
Can I create an economy؟ with Python.?
No one will stop you from doing it
so im having an issue with using sqlite on a bot hosting service
its a case of "it runs locally but broken online"
it spews this error on the host's console:
DatabaseError: malformed database schema (tmdb) - near "STRICT": syntax error
locally, the query runs just fine, im on the same python version both on the host and locally (3.11.2)
is it using different sqlite versions?
Anyway to install playwright on android? I have a discord bot that need playwright to run (yes im hosting a bot on android, it free and it work, so why not)
Whenever i tried to install it with pip on pydroid it said cant find any version that satisfied the requirements
What kind of bot hosting service you are using?
ah sorry i sorted it out
seems like the service doesn't support strict mode
which is weird
likely
it maybe doesn't support strict mode.i dont have official comments from the support team
i rebuilt the database without strict mode and voila it worked

sooo.... this is my code:
pollination_embed = discord.Embed(description="# Artwork Information:", color=0x714fff)
if isinstance(ctx.author, discord.Member) and hasattr(ctx.author, 'avatar_url'):
# If ctx.author is a Member object and has an avatar, use it as the author's icon
pollination_embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
else:
# If ctx.author is not a Member object or doesn't have an avatar, set a default icon or omit the icon_url
pollination_embed.set_author(name=ctx.author.display_name)
pollination_embed.add_field(name="Prompt used for Image Generation:", value=f">>> {prompt}", inline=False)
pollination_embed.add_field(name="Visual Setting", value=f">>> {ratio.name}", inline=False)
pollination_embed.set_footer(text=f'Creativity is inventing, experimenting, growing, taking risks, breaking rules, making mistakes, and having fun.')```
i want it to show my pfp as well.... how can i do that
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
ouch, i m def an idiot
@client.slash_command(description="Bot Information")
async def information(ctx):
embed = discord.Embed(title="Bot Information", color=discord.Color.orange())
embed.add_field(name="Bot Creator", value="duhphil", inline=False)
embed.add_field(name="Server", value="Victoria County", inline=False)
await ctx.send(embed=embed)
i'm getting an error:
Traceback (most recent call last):
File "c:\Users\phil\Desktop\projects\python\VMod\main.py", line 172, in <module>
@client.slash_command(description="Bot Information")
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
i have no clue what the issue is
whats the tree event ? for ctx one its @bot.event but what is the tree event? its not @tree.event btw
every event is registered using bot.event


