#discord-bots
1 messages · Page 360 of 1
``Traceback (most recent call last):
File "C:\Users\keykk\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\keykk\OneDrive\Documentos\guilda\main.py", line 79, in estatisticas
ico.paste(icone, (0,0), mask=icone)
File "C:\Users\keykk\AppData\Local\Programs\Python\Python311\Lib\site-packages\PIL\Image.py", line 1738, in paste
self.im.paste(im, box, mask.im)
ValueError: bad transparency mask
The above exception was the direct cause of the following exception:
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\keykk\AppData\Local\Programs\Python\Python311\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\keykk\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'perfil' raised an exception: ValueError: bad transparency mask``
i got this to work and tried it but if i change my mind on the genus it doesnt update the breed list
huh, i guess it won't refresh until you type something... thats a bit awkward
to make it update the list i have to remove the option and go again
remove the choice basically being running the slash command again
i meant typing something arbitrary into breed to refresh the autocompletion, but i guess that refreshes it too
that didnt work when i tried it
weird, i thought the point of autocomplete callbacks were to provide different options as the user typed...
is there a way to get rid of this warning permanently, the code is correct works just fine.
depending on your command, maybe a better user experience would be a select menu involving multiple interactions? i.e. they pick an option and it gives a new set of options related to that option, or a back button to return to the last set
i guess just put # noqa on that line?
i believe pycord supports num: str = Option(...) as an alternative syntax, at least based on what i can gather from their source code
https://github.com/Pycord-Development/pycord/blob/master/discord/commands/core.py#L763-L768
discord/commands/core.py lines 763 to 768
if isinstance(p_obj.default, Option):
if p_obj.default.input_type is None:
p_obj.default.input_type = SlashCommandOptionType.from_datatype(
option
)
option = p_obj.default```
# type: ignore
is in vs code
but i was wondering if there was a better way to do this...
i was hoping for slash command choices but ig that might work
just to be certain there is no way to make it update?
thanks
another idea might be to prompt each set of options in the same parameter and update it according to what they type, but it would stop autocompleting if they clicked on any of them...
discord is irritating
there is surly way to force update it?
Yo can anyone please bless up (repl.it) command for purge, been watching tutorials (all of em super old) still watched and none of em seem to work especially from a year ago, yes my bot even has admin priv too so not a portal thing or any of that sort
Helper help out? if possible
Hi,I need a bit of a guide with discord automod which I am new to. I am using a text file to block swear words till now but I want to use automod for it
If possible please help me!
Thanks 🙂
If possible please use dms
just use the automod panel in server settings?
I wanna use the bot
what bot?
Using code for doing it
you don't need a bot just to filter swear words
I don't wanna do it the old fashioned way
I want the fancy Uses automod badge beside my bot
!d discord.Guild.create_automod_rule
await create_automod_rule(*, name, event_type, trigger, actions, enabled=False, exempt_roles=..., exempt_channels=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Create an automod rule.
You must have [`Permissions.manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild) to do this.
New in version 2.0.
in your trigger, put your swear word list in the keyword_filter
How do I get words from a file called BadWords.txt and use it
read it and split words
As the trigger
Eample
i'm trying really hard not to give you the code straight up
trigger = AutoModTrigger(
type=AutoModRuleTriggerType.keyword,
keyword_filter=["fuck", "shit", "rust"],
)
then pass that in to create_automod_rule
Ohk ok thats
i'm assuming you already know how to read the words from the text file
Ya ok
just pass in the list to keyword_filter
you don't do anything in on_message
just make a command the creates the rule and discord handles that for you
Ohk thanks 👍
Like? I'm new to automod so please help 😦
rust 
if i want my bot to play audio in a vc which one do i use?
pcm audio has the stream attribute but is it the one i should use? and how
also why does this raise an exception? .voice.channel should be a thing but it says: 'NoneType' object has no attribute 'channel'
if not interaction.guild.voice_client and member.voice.channel == interaction.guild.voice_client.channel:
This comes back to when I told those two off several hours ago
Member.voice is VoiceState | None, meaning it is possibly None (when the member has no cached voice state)
You'll need to check it's not None before accessing attributes of VoiceState
As for playing audio, you likely want FFmpegPCMAudio or FFmpegOpusAudio
# Check if the command invoker is in a voice channel
if member.voice:
# Check if the bot is in a vc
if interaction.guild.voice_client.channel:
# Connect to the voice channel
await member.voice.channel.connect()
await interaction.response.send_message(f"Evo me v channelu {member.voice.channel.name}!")
elif not member.voice.channel == interaction.guild.voice_client.channel:
# Connect to the new voice channel
await member.voice.channel.connect()
await interaction.response.send_message(f"Evo se premaknem v {member.voice.channel.name}!")
else:
await interaction.response.send_message("Pa sej sem že v istem klicu kot ti, kaj naj se še kloniram?")
else:
await interaction.response.send_message("Če me želiš slišati, se prvo joinaj v vc.")
this should check if the bot is not in a vc but i still get the error:
if interaction.guild.voice_client.channel:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'channel'
so if not channel what other arrtibute is there?
Guild.voice_client is VoiceClient | None meaning this can also possibly be None (which means they're not connected)
Check if it is None before trying to use it
but i did? if member.voice checks if the member who invoked the command is in a vc and if interaction.guild.voice_client.channel checks if the bot is in a vc
oh nvm my bad
the .channel is probably whats causing the problem
i was checking if the .channel is None instead of if the bot is in a vc
i copy pasted the code and forgot to remove the .channel
Your error here told you the channel attribute was part of the problem, use that to narrow it down :)
i got it thank you
i terminated the nohup process on my linux while the bot was in a vc in a server. he didnt leave the vc so i disconnected him. now for some reason only in that sever the bot wont appear online or respond to any commands even if i kick him and add him back?
nvm he only appears online in 1 single server
might wanna close and restart ur discord client if all else fails
also sometimes discord is kind of slow to update status after some gateway disconnection
nope still offline in all but 1 server
does it have anything to do with this code?
@client.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:
synced = await ctx.bot.tree.sync(guild=ctx.guild if spec == "~" else None)
else:
synced = await ctx.bot.tree.sync(guilds=guilds)
await ctx.send(f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}")
idk what else it could be
online status is irrelevant to the no. of synced commands i believe
the problem is that he wont respond to any commands and the tree of / commands wont update even after kicking the bot
thats weird
but he works fine in 1 specific server
what if i just make a new bot and replace the token
i'll try that
its working. idk why but it is
sync() doesn't take guilds=
only a single guild= at a time
(anyway, that is kinda irrelevant)
There's a bug in d.py stable at the minute that doesn't cleanup force disconnected voice clients, we think it's fixed in the upstream but the release is pending
For now I'd advise you to avoid manually disconnecting the bot
is this how the basic structure should look like?
await interaction.guild.voice_client.play(discord.FFmpegPCMAudio.from_probe("audio/n4.mp3", method="fallback"))
also i'm assuming it doesnt support mp3 to i'll convert it to webm
how can I convert the permission's integer, eg- 35461652409665 to a list of permissions in plain text?
list_of_perms = list(discord.Permissions(35461652409665))
!d discord.Permissions
class discord.Permissions(permissions=0, **kwargs)```
Wraps up the Discord permission value.
The properties provided are two way. You can set and retrieve individual bits using the properties as if they were regular bools. This allows you to edit permissions.
Changed in version 1.3: You can now use keyword arguments to initialize [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions) similar to [`update()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.update).
it supports iter which allows you to do dict and list
i got the bot playing audio using FFmpegPCMAudio. how can i stop all audio that the bot is playing?
!d g discord.VoiceClient.stop
stop()```
Stops playing audio.
This method should help, since you already know how to get a VoiceClient
How to add sticker in a guild?
damn
Damn
the bots like na
Like i didn't check😭
I was first tho. So use my link
nah i was first
Okay that helps but what about animated object turning into static 😭😭
Dont trust this @wanton current guy. he's suspicious
You both are like me and @viscid hornet
we compete too 🤣
?
na i dont compete lol, im just bored.
hi bored
besides. my link was first and therefore use mine not that sus @wanton current 's
emoji = self.data[self.index]
name = emoji.name.replace(" ", "_")
response = requests.get(self.url)
print(response)
if response.status_code == 200:
emoji = BytesIO(response.content)
emoji = await self.ctx.guild.create_custom_emoji(name=name, image=emoji.read())
await self.ctx.send(f"Uploaded animated emoji: {emoji}")
I had passed animated sticker into it but it returned static emoji
⬇️
UP DOWN TURN AROUND
The Wiggles: Up, Down, Turn Around from Ready, Steady, Wiggle! (TV Series) (Series 1).
No copyright infringement intended. All rights go to The Wiggles Pty Ltd. & the Australian Broadcasting Corporation or ABC.
:D
actually I was thinking of a real song not this nonsense i just found this one first xD
You forgetting the topic
There is no topic. Only wiggles now.
Still not resolved

you're trying to create a sticker with create_custom_emoji?
Create a emoji with a sticker
well, what is self.url?
It was this sticker and it returned

It's the url of self!
its a png
🤔
So the most two recent topics was someone making a voice bot and someone trying to make stickers.
🤣🤣
Trying avoid animated stickers turning into png/static
Making a voice is still easier
@drifting arrow i checkef format type and it returned apng
yeah it's an animated png
i get the same https://i.itswilliboy.com/LMChYQZUhF.png

huh, APNG has backwards compatibility with regular PNGs, so discord's backend probably thinks its just a PNG... you'll probably need to use pillow to re-save it in gif format
https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#apng-sequences
can someone look over my code? the slash command doesnt appear! https://paste.pythondiscord.com/7EDQ
thanks 🙂
did you sync your commands
Since i dont know what you mean by synchronizing the commands, i guess i didnt
Its my first time trying to use discord's slash commands
ah ok. you need to sync your command tree
@brave galleon
thats the link
way ahead of you 
xD
Can you not ping reply please @viscid hornet
Wait, how would that work I've never used it before?
That's not a education purpose
it is
i am jokin broski
We aint joking too
we don't help with those, educational or not
it was a joke i will just delete it
import discord
import os
intents = discord.Intents.default()
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('Token'))
Why am I not getting any response when I use the command
Enable message intents
Done it's working
Btw how to make it send a message that I wrote
Like I wrote $hello hi, then it should send hi
You'd want to use the command extension for that
!d discord.ext.commands.Bot <- docs
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin) to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree) and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
#databases message @warped cave this is with discord.py right? you can write your own check decorators to validate the user's channel and apply them to whichever commands you want it on, something like: ```py
def is_in_channel(name: str):
def predicate(ctx):
return ... # True if ctx.channel matches name, else False
return commands.check(predicate)
Usage:
@bot.command()
@is_in_channel("Cyber")
async def my_command(ctx): ...``` see also: https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#checks
shrug, ive barely used pillow too, but if you read through the tutorial and/or ask in #media-processing you can probably figure it out
https://pillow.readthedocs.io/en/stable/handbook/tutorial.html
if i were to guess, it might be something like: ```py
from PIL import Image
sticker_file = ... # in-memory file of the bytes you read from your sticker
image = Image.open(sticker_file)
with io.BytesIO() as output_file:
image.save(output_file, format="gif", save_all=True)
output_file.seek(0)
output_bytes = output_file.read()```
thank you very much i will take a look at it and try it out
I've tried something else and saved image wait I'll show you
@hushed galleon
sticker = self.data[self.index]
sticker_image = Image.open(io.BytesIO(await sticker.read()))
if sticker_image.is_animated:
frames = []
for frame in ImageSequence.Iterator(sticker_image):
frames.append(frame.copy())
frames[0].save("animated_sticker.apng", save_all=True, append_images=frames[1:], format="PNG")
print("Animated sticker saved as animated_sticker.apng")
else:
print("not apng")
I got it saved in my files
er, it looks like that just saves an individual frame instead of the entire animation
oh right, append_images= is there
@hushed galleon i now have this code and it works so that means if i copy past this and change it with the right commands and channels its good ```def is_in_channel(name: str):
def predicate(ctx):
return True # True if ctx.channel matches name, else False
return commands.check(predicate)
Usage:
@bot.command('!cypher_ascend_a')
@is_in_channel("kj")
async def my_command(ctx): cypher_ascend_a
uhh you need your predicate to check that the channel's name is equal to the string you passed, kj
do you know how to retrieve and compare the channel's name?
no, i almost dont know anything about coding tbh
ok, so with the code above, discord.py will pass a Context object to your predicate function which represents the... context, of the person invoking the command
context objects contain attributes like the .message that was sent, the .author that sent it, etc.
the one you want here would be the .channel attribute, which refers to the channel where the user sent their command in
@hushed galleon okay i used it and worked but look
Why is it blinking from lower side
🤣
the doc says Union[abc.Messageable] which is er, not that helpful, but in regular channels like #discord-bots you can assume that the channel is a discord.TextChannel object
and from that doc, you can see that TextChannel objects have a .name attribute, a string describing the name of the channel
weird, might need to file a bug report to pillow
Ehh fine for me as long as it works
This is original one
so, if you wanted to get the name of the channel in the ctx object given to your predicate function, you would write ctx.channel.name
then, to compare it to another variable you'd use the == operator, e.g. ctx.channel.name == name
that gives you a boolean value, True/False
so for me it would be ctx.channel.name == kj
Is it mandatory to save file or there could be any alternative like making a temporary instance of a file?
kind of, writing a plain kj would mean a variable named kj, not a textual string "kj"
ctx.channel.name == "kj" would be how you'd compare it to the literal string kj
it looks like save() is the main way to do it, thats why i used an in-memory file in the prior example
but i still have to use this code or is it just to give an example
Oh thanks I'll just delete them after uploading into server
it's most of the way there, the predicate function just needs to be given the code to compare the actual channel name
after you have the result of your comparison, you can return it from your predicate function, which tells discord.py that if your comparison is False, it knows to stop the command from running in that channel
but where do i put ctx.channel.name == kj in the code
so if i have this code like bellow here, where do i implement ctx.channel.name == kjbc im a bit lost it this code was good or needed some adjustments ```def is_in_channel(name: str):
def predicate(ctx):
return True # True if ctx.channel matches name, else False
return commands.check(predicate)
Usage:
@bot.command('!cypher_ascend_a')
@is_in_channel("kj")
async def my_command(ctx): cypher_ascend_a```
How to get server name? In discord.py?
Ohk
!d discord.Guild
class discord.Guild```
Represents a Discord guild.
This is referred to as a “server” in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guild’s hash.
str(x) Returns the guild’s name.
You can see all of the attributes there
Also the message which was sent by author?
ctx.message
Ohk lemme try
discord.Embed(title="⚠️ ANTI SPAM ⚠️", description=f"You have sent a swear message! Please do not use profanity in {guild.name} Your message: {ctx.message}", color=0xff0000)
I have used this
It's not working
Please help
Not exactly sure what's going on here. I've given it my best shot on solving the error, here is the code and the error
https://paste.pythondiscord.com/35BQ
what is not working?
I have made it anti swear and the message is getting deleted but the embed isn't getting sent to me in dms as it should work
it's very hard to diagnose your problem with only the embed
real
async def on_message(message):
if message.author == bot.user or message.channel.id in whitelisted_channels:
return
with open('BadWords.txt', 'r') as f:
bad_words = [line.strip().lower() for line in f]
if any(bad_word in message.content.lower() for bad_word in bad_words):
await message.delete()
embed = discord.Embed(title="⚠️ ANTI SPAM ⚠️", description=f"You have sent a swear message! Please do not use profanity in {guild.name} Your message: ```{ctx.message}```", color=0xff0000)
await message.author.send(embed=embed)
await asyncio.sleep(60)
await message.author.dm_channel.purge(limit=1, check=lambda m: m.author == bot.user)
await bot.process_commands(message)```
Didn't work
How to paste big codes
both work
How to do it
ah
Pls help i can't upload code
!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.
@hushed galleon
Anybody got a thought on this string error
def predicate(ctx):
return True # True if ctx.channel matches name, else False``` this part needs to be implemented to do what the comment says
it seems to be referring to source='-i' which isnt valid with pipe=True? dunno much about dpy's audio playing stuff
I believe it uses the pynacl library but it isn't supposed to play anything but record
i thought dpy didnt natively support voice recordings
i feel dumb for not understand this xD
I don't know. There's honestly not much documentation anywhere on how to do this
from danny:
https://github.com/Rapptz/discord.py/pull/9288#issuecomment-1785942942
As good time as any I guess, but I've been thinking about the state of the various voice receive implementations and decided that I'm probably not going to merge any of them into the mainline repository going forward. If you want a voice receive implementation they're most likely better off as extension modules (e.g. discord.ext.my_voice_recv). One of the contributors for this library has already taken the initiative to do this and is probably a better way forward since it detaches the maintenance burden from me to the person who wrote the PR.
the two extension packages i found were discord-ext-voice-recv and discord-ext-listening so you'll probably want to look into those:
https://github.com/imayhaveborkedit/discord-ext-voice-recv
https://github.com/Sheppsu/discord-ext-listening
(only the former is on PyPI, the latter must be pip installed with the git+ prefix)
Thank you. I do know for a fact that the recv one does not work with discord.py. I will give the other one a shot
there's a few examples in the documentation that might help you understand it:
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#checks ```py
def check_if_it_is_me(ctx):
# This is the predicate function, comparing the
# command author to a specific user ID
return ctx.message.author.id == 85309593344815104
@bot.command()
@commands.check(check_if_it_is_me)
async def only_for_me(ctx):
await ctx.send('I know you!') py
def is_me():
def predicate(ctx):
# Same predicate function, just written a bit differently:
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
@bot.command()
@is_me()
async def only_me(ctx):
await ctx.send('Only you!')```
oh huh, yeah the readme says it only works with the development version of dpy:
Note: This extension requires discord.py 2.4, which as of now has not been uploaded to pypi. You may need to install discord.py from github.
Thank you very much appreciated. I'll give it a shot a bit later today
it means you tried using a variable that you haven't defined, i.e. ```py
guild = ...
print(f"Message from {guild.name}")```
you can get the guild from your message object via message.guild
@bot.listen()
async def on_member_update(before, after):
server = bot.get_guild(1000824509869346827)
staffrole = server.get_role(1155546749117669376)
if staffrole not in before.roles and staffrole in after.roles:
print("Staff member has been assigned a team.")
How would I check who received the staffrole?
so if i understand it correctly i put on return ctx.channel.name == name and than the last part after the == my channel id ?
before and after are both Member objects representing the same person, so you can get their .mention, .display_name or whatever
im not sure what you mean with channel id but ya that's how you compare the name to the string you passed in your command decorator, @is_in_channel("kj")
mhm
thank you.
where can I list a channel for it so send a mesasge to whenever the command is triggered?
guild objects have a .get_channel(id) method so you can use that to get the channel object to send your message to
e.g. py channel = member.guild.get_channel(1234) if channel is not None: await channel.send("Something happened!")
i now have this but im not sure what to do with the async def only_me(ctx) ``` def is_in_channel():
def predicate(ctx):
# Same predicate function, just written a bit differently:
return ctx.message.channel.id == 1234540499390431252
return commands.check(predicate)
@bot.command()
@is_in_channel("1234540499390431252")
async def only_me(ctx):
await ctx.send('Only you!')```
thats the example command, you dont copy that
is_in_channel() wasnt defined with any parameters, so you cant pass the channel ID in @is_in_channel("1234540499390431252")
thank you, I got it to work
so the @is_in_channel("1234540499390431252") isnt working bc its not defined wiuth parameters
but how do i define it with a parameter
def add(x, y):
# ^^^^ parameters (inputs)
return x + y
# ^^^^^^^^^^ return value (output)
>>> add(1, 2)
3```
so at x i have to add my @is_in_channel ?
How can I get this to assign the user a team whenever they get staffrole?
@bot.listen()
async def on_member_update(before, after):
server = bot.get_guild(1000824509869346827)
staffrole = server.get_role(1155546749117669376)
logchannel = bot.get_channel(1235278110216159252)
if staffrole not in before.roles and staffrole in after.roles:
await logchannel.send(f"{after.mention} has been assigned a team.")
I need it to give them a team with a coresponding role, and I need it to change teams each time.
i looked it up but isnt this for like commands with 2+2 ect ? not sure
What does a "team" mean here?
Is it one specific role? Just like when they get X role also give them Y role?
Or is this like you need some kind of round robin to assign people across a set of roles?
Hi I need a code where I have a slash command called reaction and a embed is sent and when it's sent it will record time until the button Read in danger theme is clicked and Edits the embed showing the time taken to click it!
Please help cause I don't know how to do it 🙂
5 different roles
- make a list
- find some way to iterate through it. One possible way is to use
itertools.cycleand save that somewhere, such as on an attribute on your bot - when someone gets role X, get the next role from the round robin, give it to them with
member.add_roles
just send the view, call time.time(), wait for a callback and take another time.time() then calculate the time difference
one more question, how would I make a parameter optional in a slash command?
Similar to how you'd make it optional in any normal python function, by providing a default like = None
Question so like on my discord bot I have a message command tthat responds with a view with a dropdown menu. Is it possible to instead migrate that select menu to a model dialog yet (with only that slelect menu)?
nope
Pretty much all you can do is have the select open the modal and pass its value(s) into it

how I can run multiple bots on 1 file?
It's inadvisable to do so, you're not really gaining anything functional in exchange for instability
I want to control more than 1 bot from a bot
like turn them off or on or refresh them etc..
I saw someone have a bot like this
You can do that without running everything on a single python process
how?
Run multiple bots across multiple python processes, have some kind of process manager handle them individually, then have some utility interact with that process manager
he even changed a token for a bot from it
Anyone got a simple python (replit) code for purging?
No, threading still happens in one python process
which becomes more unstable and fragile the more things you put on it
I would recommend using a process manager
there are several available depending on what OS you're running on
also replit doesnt have exclusive code syntax and whatnot. its also advisable not to use replit in the first place
is there any docs for this?
Thanks 💪 and what should I be using if not replit?
VS Code doesn’t have that key option anymore like replit does
your own pc
what do you mean by “key option”?
Each process manager has extensive docs, yes. systemd is a popular one for linux systems, for example
Token
I'm windows, what should I use?
They way to store Tokens for ur bot like how in every tutorial ur bot needs a token from the developer portal which should not be shared
Windows has Task Manager built in. There may be other things you can run but I haven't messed with windows much
In order to store that token there was a specific file but that file is no longer usable after VS code updates so everyone said replit was the way
ok thx for help
you can use:
- a .env file and use os.getenv() to get the token value
- a config json file and use json.load to load the contents and use it like a dict
- a txt file and read from it
The first one env file is what I meant, it doesn’t work anymore
use a txt file. i dont see why you need .getenv() 
In VS code at least when I tried couple months back and all videos said .env file no longer works
should have been fixed by now, if there was an issue with env files
give it a google search and tel me what happens
True but I was a complete noob at the time so I didn’t know txt also worked with it lol
When I get home I’ll lyk
Appreciate the help tho big time
yeah you can just open(“token.txt”) and then .read() from it. its what i always do for my bots
You can use pretty much whatever config format you want. .toml is also a popular format. It really doesn't matter so long as you're not committing it to source control


.py and use the built-in import.
.wav of Morgan Freeman narrating your config
My commands rn are really unorganized and alot of code all if statements like this if message.content.startswith('$test'): 💀
Whats a good way to organize them and maybe even turn them into / commands?
Preferably if possible Id like each cmd to be a seperate file but idk
An entire file for each command is pretty overkill. Long files aren't bad, poorly organized ones are
so how can I organize it better??
Either way, splitting things between files is a separate decision from using prefix or slash commands
If you want to use prefix commands, you should be using the commands extension rather than if statements in a message listener
I want to switch to slash but I just wanted to get the bot working firsy
now that it is I wanna switch to slash and format the code better
Well if you want slash commands, that's a separate migration and they have different behavior/features
Depends on which library you're using
alr well idk if I wanna break everything rn by trynna switch so Ill just stick to trynna organize it. what can I do for that?
If using discord.py, the commands extension to declare your commands
send docs
First Google result for discord.py commands extension
There's also a comprehensive example of a bot with a few commands in the repo's example folder
ohh yea ive seen that
But I dont understand, whats the ctx left: int, right: int etc
a thorough walkthrough for ext commands from dpy is https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#ext-commands-commands
All command methods get a ctx, this is an object containing a bunch of metadata about how the command was run. Then you choose how many other parameters you want from the user, if any
are there any docs like this on switching to / commands?
nop, been waiting for it since forever, best thing you have is a mod's docs
Discord.py allows for several ways to create/define application commands within it’s codebases. In this page we’ll go through several of these.
I'm just "a mod" now :(
wdym what am i suppose to say, 'nerd'
2024-05-02 00:55:18 ERROR discord.client Ignoring exception in on_member_remove
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/bot.py", line 44, in on_member_remove
await channel.send(f"{member} bye mf")
AttributeError: 'NoneType' object has no attribute 'send'
``` ```py
@bot.event
async def on_member_remove(member):
channel = bot.get_channel(11981747783396230033)
await channel.send(f"{member} bye")``` i do not kow what i did worng any thots
Your bot does not have a channel with that id cached
can u fetcch the rules or guidelines channel from the community settings under the guild object?
whats the member join event?
it's called when a member joins a server your bot is in
yea but what is the event.?
whats the code for it
same as any other event:
@bot.listen()
async def on_member_join(member: discord.Member):
...
This issue is caused because the channel with the ID 11981747783396230033 does not exist or the bot does not have access to it.
!d discord.Guild.rules_channel perhaps
property rules_channel```
Return’s the guild’s channel used for the rules. The guild must be a Community guild.
If no channel is set, then this returns `None`.
New in version 1.3.
Anyone has any way to have antispam and the spam work if the channel is as whitelisted_channel
something to do with automod
No one shows me how to use discord automod with dpy 😦
there was some stuff earlier in this channel about automod
Idk
!d discord.Guild.create_automod_rule
await create_automod_rule(*, name, event_type, trigger, actions, enabled=False, exempt_roles=..., exempt_channels=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Create an automod rule.
You must have [`Permissions.manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild) to do this.
New in version 2.0.
also im half awake so not the time for questions 😂
I can't understand how it works dm me if anyone can help in detail 🙂
link you do this
DM help is not advisable at all for many reasons,
Please outline what exactly you need help with relating to automod?
Hopefully I can help, I'm the one who added it to d.py
I don't know anything about automod with dpy
|| oh wow. congrats to you and thank you for adding it 👍🏽 ||
im gonna go now, bye 👋🏽
Again this isn't a clear way to ask for help. What do you want help with? What's your end goal
Anti spam and anti swear
I am using async def on_message for now
There, that's something we can work with.
Okay, the documentation above for Guild.create_automod_rule is where to start with this, open up the documentation and have a look at the parameters the method call takes and we can talk through it
Seen
Okay, well, going from that documentation what parameters confused you
Exactly
I have -10 IQ
Nothing got into my brain
I can't help you if you're not willing to apply some effort with me, and I don't think handing you things on a platter is a good way to learn. So how about you read that documentation again and look at the parameters, maybe try and write some code using them and we'll take it from there
Happy to help but only if the other participant(s) are willing too.
async def on_ready(self):
await self.change_presence(
status=discord.Status.idle,
activity=discord.Activity(type=discord.ActivityType.watching, name="your messages")
)```
This is the code, the problem I'm facing with it is that the bot is not going in idle mode, but its activity is correct
I am
You shouldn't do this in the on_ready callback, and instead set them on the Client/Bot constructor with the activity and status kwargs
Oh sure
Alex help me bruh i will put effort
I already asked you to do something :)
code:
def getButtonStyle(self, view: str, button: str) -> str:
return str(self.messagesData.get("views", {}).get(view, {}).get(button, {}).get("style", "green"))
error
button_style_obj = discord.ButtonStyle[configManager.getButtonStyle(msg, label1)]
TypeError: ConfigManager.getButtonStyle() takes 2 positional arguments but 3 were given
WTF?
where is the third argument?
(You have created a "bound method" meaning it requires a full class instance to call, hence the self argument)
what is a "bound method" ?
A method which is bound to the class where it is defined
example?
class Foo:
def bar(self) -> None:
print(repr(self))
bar is a bound method of Foo
Meaning you need an instance of Foo to call bar:-
obj = Foo()
obj.bar()
I have it configManager = ConfigManager("configs/config", "configs/messages", "configs/warnings", "configs/commands", "configs/levels")
show the definition of getButtonStyle
you probably forgot self
.
did you save? this should work
add a parantheses after configManager?
No I was mistaken upon reading their code
Their issue is something else, it looks like a difference between runtime and shown code.
how?
class ConfigManager:
def __init__(self, file_path, messages_path, warnings_path, commands_folder, levels_path):
self.config_path = file_path
self.message_path = messages_path
self.warning_path = warnings_path
self.command_folder = commands_folder
self.levels_path = levels_path
self.levelsData = self._readJSON(levels_path)
self.warningsData = self._readJSON(warnings_path)
self.configData = self._readJSON(file_path)
self.messagesData = self._readJSON(messages_path)
yes i did.
I don't need to.
There's a discrepancy between your error and your code, ensure your file is saved and everything necessary has been reloaded/restarted
I restarted pycharm and same error.
how do you call this method
.
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
you have to use parantheses
but the error is in the getButtonStyle
button_style_obj = discord.ButtonStyle(configManager.getButtonStyle(msg, label))
TypeError: ConfigManager.getButtonStyle() takes 2 positional arguments but 3 were given
still not working.
I haven't used discord.py in a long time but I know what's wrong
just try to get me on this one
what does this getButtonStyle return?
string like green
so you need to do something like
discord.ButtonStyle.green
How did you define configManager?
button_style_obj = getattr(discord.ButtonStyle, getButtonStyle(msg, label1)
try this
@quaint obsidian ^^
button_style_obj = getattr(discord.ButtonStyle, configManager.getButtonStyle(msg, label))
TypeError: ConfigManager.getButtonStyle() takes 2 positional arguments but 3 were given
Please fully exit/close and restart your bot AFTER you ensure your file is saved and up to date
Yeah ig maybe your editor is acting up
Ok. It is saved.
button_style_obj = getattr(discord.ButtonStyle, configManager.getButtonStyle(msg, label))
TypeError: ConfigManager.getButtonStyle() takes 2 positional arguments but 3 were given
Okay something is definitely fishy. Can you upload the whole file causing this issue here?
!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.
Need the definition of ConfigManager too
@spice warren Do you play helldivers 2?
Wanna play sometime? I was looking for someone to play with, because alone is kind of boring and sometimes hard.
So does anyone have any idea why is that? I ran th bot with cmd and still the same thing.
this paste does not exist
How can u check if no message is sent in a channel in a minute?
i'm making a bday bot and i found online to either use tasks or schedule, i'm trying to use tasks here but idk how to get the fn started. it's telling me to use asyncio but then i have to add like 30 lines of code and it still doesnt work:
@tasks.loop(minutes=1)
async def bdaydatecheck(interaction: Interaction):
today_date = datetime.now().strftime("%d.%m")
# Remove leading zeros from the month as well
today_date = today_date.replace("0", "")
channel_to_upload_to = client.get_channel(1235528733520166912)
# Iterate through each entry in the birthdays data
for name, date in birthday_messages.items():
# Split the date string at the dots to extract day and month
day, month, year = date.split(".")
# Check if the date matches today's date
if today_date == (f"{day}.{month}"):
........
when this was a command and i called it it successfully checked if its someone's bday. i just dont know how to automate it to run daily at 8am
You start these kind of task loops with task_func.start(). So it's bdaydatecheck.start() in your case (make sure to start it after the bot is already running)
i tried that but i pasted the code before the client.run.
are you using wait_for?
i tried it like this:
# CONNECT
client.run(TOKEN)
bdaydatecheck.start()
and it never started. after i closed the bot i got errors: https://paste.rs/8cvdz.py
a simple, no-frills, command-line driven
pastebin service powered by the Rocket web framework.
Why is it not working on same channel but if I use it on another channel it's working fine?
@gusty berry can yo help?
client.run is an endless loop and will never let code run below it
but if i paste it in i get these errors:
Traceback (most recent call last):
File "c:\Users\delta\Documents\Koda\Python\zoroja_bot\zoroja.py", line 261, in <module>
bdaydatecheck.start()
File "C:\Users\delta\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\ext\tasks\__init__.py", line 398, in start
self._task = asyncio.create_task(self._loop(*args, **kwargs))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.12_3.12.1008.0_x64__qbz5n2kfra8p0\Lib\asyncio\tasks.py", line 417, in create_task
loop = events.get_running_loop()
^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: no running event loop
sys:1: RuntimeWarning: coroutine 'Loop._loop' was never awaited
do i put it into the on_ready fn?
the fn.start()?
thats exactly what i had to do. ty for the help
that wasnt meant to sound sarcastic
better to put them in Bot.setup_hook
on_ready just triggers multiple time in a bot's life cycle
No what is that
import discord
from discord.ext import commands
from discord import app_commands
from typing import Optional
class spam(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def spam_check(self, interaction: discord.Interaction):
print("hi")
async def setup(bot: commands.Bot):
await bot.add_cog(spam(bot))
Why does it say no module named cog
Ok I have a problem. Why the view doesn't have any buttons?
def _buildButtonData(bot: commands.Bot, msg: str, placeholders: dict) -> discord.ui.View | None:
if not configManager.hasButton(msg):
return None
# msg is view
allButtonLabels: list = configManager.getButtonsByView(msg)
eph = configManager.getEphPlaceholder()
class TempView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@staticmethod
def test():
return "yes" if configManager.isActivePlaceholder(eph) and eph in msg else "no"
async def on_timeout(self):
for child in self.children:
child.disabled = False
for label in allButtonLabels:
comb: str = msg.replace(" ", "") + " " + str(label).replace(" ", "")
style = getattr(discord.ButtonStyle, configManager.getButtonStyle(comb))
custom_id = configManager.getButtonCustomID(comb)
@discord.ui.button(label=label, style=style, custom_id=custom_id)
async def onPress(interaction: discord.Interaction, button: discord.Button):
print("Help")
# Dynamically create the button press method inside TempView class
setattr(TempView, f'{label.replace(" ", "_")}_callback', onPress)
return TempView
Bump
What is that file named?
either the indentation broke or you just need to learn python
I know python, but I have no idea why it does that.
cause the for loop is outside the class
but anyways you cant create class methods inside a for loop
you need to use .add_item
I think for loop has bad indentation
i'm trying to add a reaction to a message. i've been looking at the docs and idk what else to change:
message: Message = await interaction.response.send_message(f"Datum {date} je že v bazi podatkov pod imenom {nameArr}.")
await message.add_reaction("❌") # Add the first reaction
await message.add_reaction("✅") # Add the second reaction
# Define a function to check if the reaction is from the command invoker
def check(reaction, user):
return user == interaction.user and str(reaction.emoji) in ["❌", "✅"]
# Wait for a reaction from the command invoker
reaction, _ = await client.wait_for("reaction_add", check=check)
# Determine the bool value based on the reaction
if str(reaction.emoji) == "❌":
bool_value = False
else:
bool_value = True
# Now you have the bool value based on the reaction
await interaction.followup.send(f"The bool value based on your reaction is: {bool_value}")
the error is: AttributeError: 'NoneType' object has no attribute 'add_reaction'
at the line where i try to add the 1st reaction
cause .send_message does not return a Message object
you need to use this
!d discord.Interaction.original_response
await original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
If the interaction response was a newly created message (i.e. through [`InteractionResponse.send_message()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.send_message) or [`InteractionResponse.defer()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse.defer), where `thinking` is `True`) then this returns the message that was sent using that response. Otherwise, this returns the message that triggered the interaction (i.e. through a component).
Repeated calls to this will return a cached value.
So the loop needs to be in the class?
It worked. OMG. I don't know any it didn't worked with setattr
you know what setattr is?
Yes. You can add new functions or properties to the class.
i mean technically it could have worked
but there literally is a method to add new components to view .add_item()
.add_item() adds a button, but I can't give that button a callback to be called when it is pressed.
where?
using a subclass
I tried that already. Didn't worked.
what did you try then
class ButtonCreation(discord.Button):
# init needs ctx and at best custom_id or row to do all you need
def __init__(self, label, style, emoji, custom_id, row):
super().__init__(label=label, style=style, custom_id=custom_id, emoji=emoji, row=row)
async def callback(self, interaction):
pass
and what doesnt work in this
callback didn't run.
how did you add this button to view
in the __init__ in my view I added with .add_item
mkay well it must have worked
here is the example from discord.py
that uses Button subclassing
examples/views/tic_tac_toe.py line 84
self.add_item(TicTacToeButton(x, y))```
the buttons are added here
is discord.Button even a thing
yes
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
this is a thing
it's not made to be used
!d discord.Button
class discord.Button```
Represents a button from the Discord Bot UI Kit.
This inherits from [`Component`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Component).
Note
The user constructible and usable type to create a button is [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button) not this one.
New in version 2.0.
it requires state
ic
read the last line?
def _buildButtonData(bot: commands.Bot, msg: str, placeholders: dict) -> discord.ui.View | None:
if not configManager.hasButton(msg):
return None
# msg is view
allButtonLabels: list = configManager.getButtonsByView(msg)
eph = configManager.getEphPlaceholder()
class TempView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
for label in allButtonLabels:
comb: str = msg.replace(" ", "") + " " + str(label).replace(" ", "")
style = getattr(discord.ButtonStyle, configManager.getButtonStyle(comb))
custom_id = configManager.getButtonCustomID(comb)
class ViewButton(discord.ui.Button):
def __init__(self, **kwargs):
super().__init__(**kwargs)
async def callback(self, interaction: discord.Interaction):
print("Help")
self.add_item(ViewButton(label=label, style=style, custom_id=custom_id))
@staticmethod
def test():
return "yes" if configManager.isActivePlaceholder(eph) and eph in msg else "no"
async def on_timeout(self):
for child in self.children:
child.disabled = False
return TempView
This worked.
you shouldnt be creating classes inside a function
then how can I do it?
put the class outside
But I have n amount of buttons.
if you need anything inside the class that you get from a function get it by __init__
better?
def _buildButtonData(bot: commands.Bot, msg: str, placeholders: dict) -> discord.ui.View | None:
if not configManager.hasButton(msg):
return None
# msg is view
allButtonLabels: list = configManager.getButtonsByView(msg)
eph = configManager.getEphPlaceholder()
button_data = []
for label in allButtonLabels:
comb: str = msg.replace(" ", "") + " " + str(label).replace(" ", "")
style = getattr(discord.ButtonStyle, configManager.getButtonStyle(comb))
custom_id = configManager.getButtonCustomID(comb)
class ViewButton(discord.ui.Button):
def __init__(self, **kwargs):
super().__init__(**kwargs)
async def callback(self, interaction: discord.Interaction):
print("Help")
button_data.append(ViewButton(label=label, style=style, custom_id=custom_id))
class TempView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
for button in button_data:
self.add_item(button)
@staticmethod
def test():
return "yes" if configManager.isActivePlaceholder(eph) and eph in msg else "no"
async def on_timeout(self):
for child in self.children:
child.disabled = False
return TempView
def func(n: int):
class X:
def do_something(self):
print(n)
X().do_something()
instead:
class X:
def __init__(self, n: int)
self.n = n
def do_something(self):
print(self.n)
def func(n: int):
X(n).do_something()
how can this be better if you still keep having class definitions inside a function
hey i have the same kinda issue with pyqt5
classes and functions
can u help its actually in #user-interfaces
I will just use this with the for loop fixed.
if you dont care you can use your code if it works, just saying how things should be done
i have a birthdays.json file full of text like this:
{"ziga/makuc": "7.3.2007", "liam": "26.4.2007", "abel": "14.10.2007", "ler": "1.9.2007", "kevin/kekec": "26.7.2007"}
i can easily access it but what i want to do is append a name to the names already in the file. for example to add toby to abel so it'll look like: "abel/toby": "date" and idk how to do that. i have a fn which saves back to the .json file and one that loads from it so that isnt a problem. when i use birthday_messages[bday_name] i get the date, but idk how to access and modify the names
!e ```py
data = {"ziga/makuc": "7.3.2007", "liam": "26.4.2007", "abel": "14.10.2007", "ler": "1.9.2007", "kevin/kekec": "26.7.2007"}
key = "abel"
data[f"{key}/toby"] = data.pop(key)
print(data)
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
{'ziga/makuc': '7.3.2007', 'liam': '26.4.2007', 'ler': '1.9.2007', 'kevin/kekec': '26.7.2007', 'abel/toby': '14.10.2007'}
but the code is in a separate file.
# Update the existing string value with the new name
existing_string = birthday_messages[bday_name]
print(existing_string)
updated_string = f"{name}/{existing_string}"
print(updated_string)
birthday_messages[bday_name] = updated_string
save_birthdays(birthday_messages)
this is what i tried but it only modifies the date
i'll try to modify it a bit give me a min
i got it thank you.
👍
is there a way for me to clear all of the messages from 1 channel without getting rate limited?
or would a better approach be to delete the channel and create a new one with the same name?
you can clone, delete
yeah
Full dot notation path to Class.method is needed
Oh
!d discord.TextChannel.clone
await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clones this channel. This creates a channel with the same properties as this channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to do this.
New in version 1.1.
!d discord.abc.GuildChannel.clone or actually this since it applies to all channel types
await clone(*, name=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Clones this channel. This creates a channel with the same properties as this channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to do this.
New in version 1.1.
better?
class ViewButton(discord.ui.Button):
def __init__(self, data: dict, **kwargs):
super().__init__(**kwargs)
self.data = data
async def callback(self, interaction: discord.Interaction):
print("Help")
class TempView(discord.ui.View):
is_active_placeholder = False
allButtonLabels = []
view = ""
def __init__(self):
super().__init__(timeout=None)
if len(self.view) > 0:
for label in self.allButtonLabels:
comb = self.view.replace(" ", "") + " " + str(label).replace(" ", "")
style = getattr(discord.ButtonStyle, configManager.getButtonStyle(comb))
custom_id = configManager.getButtonCustomID(comb)
self.add_item(ViewButton(label=label, style=style, custom_id=custom_id, data={}))
async def on_timeout(self):
for child in self.children:
child.disabled = False
def _buildButtonData(bot: commands.Bot, msg: str, placeholders: dict) -> discord.ui.View | None:
if not configManager.hasButton(msg):
return None
eph = configManager.getEphPlaceholder()
TempView.view = msg
TempView.allButtonLabels = configManager.getButtonsByView(msg)
TempView.is_active_placeholder = configManager.isActivePlaceholder(eph) and eph in msg
return TempView
I care. I want to be better.
hmm may i ask why are you returning a class itself not an instance?
Because I have a function that later on calls it.
mhm but you know you can create an instance before and then just pass it
Yes, but that way if the rest of the options are incorrect and the view doesn't make it to the end the instance is not created and maybe that is some kind of optimization.
mhm well thats fine
So is it good enough?
take the channel id as arg.
you dont, you get a channel object using .get_channel
get the name from interaction and put it in the parentheses?
so TextChannel.get_channel.clone()?
no .get_channel is a method of Bot or Guild
so if you have an interaction you can do interaction.guild.get_channel(channel_id)
and this will return you the channel Object
which you can then use clone method on
await interaction.guild.get_channel(interaction.channel_id).clone()?
try
i have with different code. i always get Unknown Integration
then show that code
@client.tree.command(name='clear', description='Text')
async def clear(interaction: Interaction):
channel = await interaction.guild.get_channel(interaction.channel_id)
channel.clone()
# Check if the user has the necessary permissions
# if interaction.guild.channel.permissions_for(interaction.user).manage_messages:
# # Clone the channel to preserve its settings
# else:
# await interaction.response.send_message('Text', ephemeral=True)
.get_channel is not awaitable but .clone is
mb
and instead of manual permission checks
you can just use .has_permissions check
!d discord.app_commands.checks.has_permissions
@discord.app_commands.checks.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the permissions given by [`discord.Interaction.permissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.permissions).
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions).
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0...
channel = interaction.guild.get_channel(interaction.channel_id)
await channel.clone()
it still doesnt work
what is the error
yea
it works now but when it copies the channel it moves it all the way down to the bottom of the text list
well i guess you can then .edit new channel and change its position
i have some code which outputs to a specific channel and needs it's id. if it changes it wont work anymore. is the best solution to read and update the id to a .json file?
more likely to a db
what is that?
database
The many reasons why you shouldn't use JSON as a database, and instead opt for SQL.
earlier when i was working with birthdays.json would it have also been better to write them to a database? and by that do you mean a database that is literally being hosted somewhere else?
you can have a database file based like for example sqlite
you would have a file ending with .db or .sqlite or .sqlite3 i guess .db is the best
i mean they all do the ssame
does linux support all of them or is that why sqlite3 exists?
if you can have a file it means you can have it (yes it works on linux)
@viscid hornet
?
How can I activate the discord community in python discord?
can you have your database in a file like a .txt
🤷🏽♂️
no then it would be a text file not a database file
can you use an unmarked file
doubt it
if entry.action == discord.AuditLogAction.role_update:
after = entry.after
before = entry.before
if entry.before != entry.after:
await after.edit(name=before.name, ....)```
```py
0|bot | [2024-05-02 15:51:08] [ERROR ] discord.client: Ignoring exception in on_audit_log_entry_create
0|bot | Traceback (most recent call last):
0|bot | File "/path/to/venv/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
0|bot | await coro(*args, **kwargs)
0|bot | File "/", line 352, in audit_log_entry
0|bot | await after.edit(
0|bot | ^^^^^^^^^^
0|bot | AttributeError: 'AuditLogDiff' object has no attribute 'edit'```
@pale zenith
Yeah you can't edit those
you need to edit the (uhh what is it called??) target?
yeah I think entry.target.
How can I activate the discord community in python discord?
you dont
?
This requires a human to agree to certain expectations from discord
but I want the old target
but target.before doesn't exit
exist*
The concept of an "old" or "new" target doesn't make sense (in the context of audit logs). It is going to always be the role (or other object).
but it is role update so I want the old role that wasn't updated
and I want to make the new role the older one again
so I'll need to use on_guild_role_update?
I mean, file extensions don't really mean anything, they only tell your OS (and you) what format the data contained in the file is in. I can rename a .png file to .txt and it'll still be in .png format.
hello guys can someone help me to program a discord bot?
the main function is that if someone in the server starts to play a game the bot is going to send a message into the server like --> xy started to play minecraft or something
you probably want this: https://discordpy.readthedocs.io/en/stable/api.html#discord.on_presence_update
!d discord.Member.activity
property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities).
this as well 
@pale zenith
you can. You can also use entry.before and entry.after as you already do
Yeah
but it is not supposed to say that entry.after.edit doesn't exist
entry.target.edit
before and after are the diff objects that show the changes made.
you mean
await entry.target.edit(name=before.name)```
you cannot edit a diff object
alr ty
when i run this code i get the error: Command 'bdayadd' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook
https://paste.rs/DFWJJ.py
a simple, no-frills, command-line driven
pastebin service powered by the Rocket web framework.
the code is in the link
the code does what it's suppose to but doesnt return a response and gives that error
unknown webhook tends to happen when you use followup or original_response methods before you send your initial response
i think i got it. thank you
Hey Guys,
Trying to install this discord bot:
https://github.com/SamSanai/VoiceMaster-Discord-Bot
But when i start the bot i got this errors:
root@discord-bots:~/VoiceMaster-Discord-Bot# python3 voicecreate.py
Logged in as
FlumeZ Auto Voice Channel
9790201838
------
/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py:618: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Failed to load extension cogs.voice.
Traceback (most recent call last):
File "voicecreate.py", line 28, in on_ready
await bot.load_extension(extension)
TypeError: object NoneType can't be used in 'await' expression
How can i fix it ?
Discord bot that creates voice channel temporarily by joining preexisting channel and deletes it when the channel is empty in discord.py - SamSanai/VoiceMaster-Discord-Bot
This probably wants a 2.0+ version of discord.py despite not denoting that in its requirements
How can i change the version ?
Upgrade it through pip
Pretty new at it can you explain how please ?
Google is your friend here, upgrade pip package
any1 know how i can set a default choice for slash commands using choices? ive tried to google it and nothing has come up
@app_commands.command(name="skins", description="Get the skins of an R6 account.")
@app_commands.choices(platform=[
app_commands.Choice(name="uplay", value="uplay"),
app_commands.Choice(name="psn", value="psn"),
app_commands.Choice(name="xbl", value="xbl"),
])
async def skins(self, interaction: discord.Interaction, username: str,
platform: app_commands.Choice[str] = "uplay") -> None:
try:
user_id = await self.bot.ubi.get_user(username=username, platform=platform.value)
i want the uplay choice to be the default choice, and I obviously cant make the string the default value because strings dont have an attribute called value, i understand i can just change the code, but i assume theres an actual way in discord.py?
You're not passing in a valid token
How?
discord developer portal
Iirc there's some setting on the portal that makes your bot http only, may want to look for that. Otherwise it should be pretty simple, just copy paste token and restart
This is the bot settings
Should i try to reset the token ?
Worth a shot
i dont think you can set a default choice
Probably worth contacting whoever owns that code if their code isn't working
thanks
and ppl can also type anything they want so choices are not a hard lock on which user can type
ik theyre not a hard lock i just didnt want to write an extra line of code if i didnt have to
since it would be more efficient if i could set default choices
you can probly put the choice you prefer at the start so it selects that first
i think this is the best option you got
if date == bday_date:
await interaction.response.send_message(f'Datum `{date}` je že v bazi podatkov pod `{nameArr}`.\nAli želiš dodati `{name}` v to tabelo?\nČe izbereš ❌ bo shranilo ime `{name}` kot posamezna oseba.')
message: Message = await interaction.original_response()
await message.add_reaction('❌') # Add the first reaction
await message.add_reaction('✅') # Add the second reaction
# Define a function to check if the reaction is from the command invoker
def check(reaction, user):
return user == interaction.user and str(reaction.emoji) in ['❌', '✅']
# Wait for a reaction from the command invoker
reaction, _ = await client.wait_for('reaction_add', check=check)
# Determine the bool value based on the reaction
if str(reaction.emoji) == '✅':
birthday_messages[f'{bday_name}/{name}'] = birthday_messages.pop(bday_name)
save_birthdays(birthday_messages)
await interaction.edit_original_response(content=f'Ime `{name}` uspešno dodano.')
return
```
in this code if anyone but the owner of the server tries reaction to a message the check fn never gets called. but if it's the owner it works just fine
Hey all!
Regarding hosting a discord bot:
I know there are cloud services etc, but I was wondering.
Is it possible to run a bot on a raspberry pi?
If so, any opinions on this?
Is it not better to use pm2 to start\stop\manage the bots ?
the process manager for node.js apps? or is there another pm2 you're referring to
Yea you can use it for nodejs and also for python
systemd is good
shrug, use whatever process manager floats your boat
Oh cool!
Okay, I'll come back to that once I've got one.
- Would you say it works well?
- Any special models of pi's I need to look for? (recommendations?)
i guess it was mostly fine, having 64-bit made installing pypi dependencies much easier (numpy/Pillow in particular), but i had a few annoying issues randomly pop up, related to wifi power saving and network services which required me to plug in a keyboard and monitor to fix it
besides that, its been running without intervention
dont have any suggestions for models, i just know that compiling python and other stuff like sqlite takes a while as usual
compiling is just needed to get the code working right? after that it will run somewhat the same speed as a baby computer?
Okay, will have to look into that, but you say 64 bit for easier compiling. gotcha 🙂
actually i misworded that, it saved me time by not needing to compile pypi dependencies since those packages had aarch64 wheels already compiled
Hi guys, does anyone have an open source bot that I can store for creating Temp VC?
I tried to install this bot:
https://github.com/InterfaceGUI/Discord-TempVoice-Bot
But it doesn't work
what is best for a sqlite3 db .db or .sqlite3?
no difference
imo .db, maybe .sqlite, but whatever you call it doesn't matter too much
Thanks! 🙂 good info
for your previous attempt, did you try installing discord.py==1.7.3 instead? that traceback suggests its incompatible with 2.0+
I installed this bot successfully but while trying to create vc its giving me errors
well your guild table doens't exist
its not my code
is there a schema
eek, the maintainer only has a voice.db file in their repo
rip
I reinstalled this bot again and now i cannot see this error but still cannot understand how to setup the channel that creating the VC channels
aplicattion.db?
looking at their code, it doesnt seem to be too complicated - have you tried writing your own bot? depending on what you need, you can ignore the database stuff and hardcode your VC channel
although, i thought discord had strict ratelimits on channel creation/edits?
2/10 on channel edits
I didnt tried to write my own bot
hello i have a code to my bot that can kick,ban and stuff but when i do itt it doesnt work i kinda need help i checked the code and the bot permw
would be nice if someon helps
i did a test with aiohttp to create and edit a text channel, the ratelimit i got was 2000/daily and 10/10s (unless reset-after increases, in which case it would be 10/100s)
when was this
five minutes ago
with a 3* server bot
and here's the script i wrote https://paste.pythondiscord.com/HDIQ
silent change then?
if 'snowman' in message.embeds[0].author.name.lower():
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'lower'```
my tries:
```py
if message.embeds and message.embeds[0].author is not None and type(message.author.name) is not type(None):
if 'snowman' in message.embeds[0].author.name.lower():```
the last one actually works if i just put None instead of message.author.name
oh
i see my problem
tysm
i feel like a dumbhead
why are you checking type() instead of just message.author.name is not None
i found my mistake
its supposed to be message.embeds[0].author.name is not None:
sometimes the most basic thing which is not even a bug can annoy for hours
i feel like there'd be a simpler way lol
In what event would the author be none?
When an author isn't set? It's an optional field
But if it's your own bot, and you have code that relies on the author, why wouldnt you set it?
maybe its a message sent by something else?
idk man, seems sus
in an event where other bot's embed field does not have an author set
class ConfirmButton(discord.ui.Button):
def __init__(self):
super().__init__(label="Confirm", style=discord.ButtonStyle.grey, custom_id="confirm")
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.grey, custom_id="confirm")
async def confirm_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
options = [
discord.SelectOption(label="PayPal", description="Pay with PayPal"),
discord.SelectOption(label="Credit Card", description="Pay with Credit Card"),
discord.SelectOption(label="Bitcoin", description="Pay with Bitcoin"),
discord.SelectOption(label="Ethereum", description="Pay with Ethereum"),
discord.SelectOption(label="Apple Pay", description="Pay with Apple Pay"),
discord.SelectOption(label="Google Pay", description="Pay with Google Pay")
]
select = discord.ui.Select(placeholder="Select Payment Method", options=options)
select_view = discord.ui.View()
select_view.add_item(select)
embed = discord.Embed(
title='Select Payment Method',
description='Please select your payment method.',
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed)
class opened_ticket(discord.ui.View):
def __init__(self, ticket_channel):
super().__init__()
self.ticket_channel = ticket_channel
@discord.ui.button(label="Proceed", style=discord.ButtonStyle.grey, custom_id="proceed")
async def proceed_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
title='How much robux would you like to buy? (1/4)',
description="""
Example: **10,000**\nThe minimum order amount is **10,000** Robux
""",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed)
def check(msg):
return msg.author == interaction.user and msg.channel == interaction.channel and msg.content.isdigit()
while True:
try:
msg = await self.bot.wait_for('message', check=check, timeout=60.0)
except asyncio.TimeoutError:
return await interaction.followup.send("You took too long to respond.", ephemeral=True)
robux_amount = int(msg.content)
if robux_amount < 10000:
embed = discord.Embed(
title='Amount too low',
description='The minimum order amount is **10,000** Robux',
color=discord.Color.dark_red()
)
await interaction.followup.send(embed=embed)
else:
break
self.robux_amount = robux_amount
embed = discord.Embed(
title=f"Confirmation (2/4)",
description=f"Are you sure you want to buy **{self.robux_amount:,}** Robux?\nCurrent Rate: **$2.1 per 1,000**\nPrice in USD: **${(self.robux_amount / 1000) * 2.1:,.2f}**",
color=discord.Color.green()
)
confirm_view = discord.ui.View()
confirm_view.add_item(ConfirmButton())
await interaction.followup.send(embed=embed, view=confirm_view)```
Why confirm button doesn't do anything 
its supposed to be within view i think not in the button super init
I want to make the bot to execute a application command AKA /addrole user_id but bot.get_command() will only work ctx commands and not application. How can I do it?
Why are you trying to use get_command?
Also it's worth noting that people can already add roles manually natively in the UI, and this potentially allows people to escalate above things they'd otherwise be able to do
that was just an example.
I want to make a custom bot.
!d discord.app_commands.CommandTree.get_command
get_command(command, /, *, guild=None, type=<AppCommandType.chat_input: 1>)```
Gets an application command from the tree.
@slate swan will it work if the application commands are in cog?
should
is it possible to use discord.py and forks together?
probably. but why would you ever want to do that though
You won't get support from either even if it is possible
i’ve seen a couple forks like pycord, disnake and nextcord who dont support having both libraries installed
would they even work together in the first place?
No
i was just wondering and wanted to use interactions.py with discord.py
why do you want to do that
discord.py already supports interactions
i found interaction.py's modal creating a bit simpler and for some other features that i liked
it has to be one or the other unfortunately
its like trying to build a car with the parts of two cars stripped apart
you can probably replicate it by making your own abstraction on top of discord.py
@bot.tree.command(name="mute", description="Mutes the user via discord's timeout function.")
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str, duration: int):
try:
await member.timeout(reason=reason)
await member.send(f"You have been timed out from {interaction.guild} for {reason}")
await interaction.response.send_message(f"Successfully timed out {member} for {duration}")
except discord.Forbidden:
await interaction.response.send_message(f"Successfully timed out {member} for {duration}, however a DM explaining why could not be sent to the user.")
how can I set the duration here using discords timeout feature
!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).
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#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).
anyone here that can help?
dont ask to ask
i got some bot code and a seperate file called ping.py in a commands folder
the ping.py is
from discord.ext import commands
class Ping(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ping(self, ctx):
await ctx.send('Pong!')
def setup(bot):
bot.add_cog(Ping(bot))
its saying that its not defined, any reason why?

Are you loading the cog?
initial_extensions = ['commands.ping']
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
bot.load_extension(f'commands.{filename[:-3]}')
yea
surprised you didnt get a tracemalloc error from this
you need to await your load exts
actually it gives me a warning abt that
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
anything tracemalloc 99% of the time is to do with that line not being awaited
i'll try it out thanks
how I can control multiple discord bots from 1 bot
like restart them or change their tokens etc..
if __name__ == "__main__":
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
try:
bot.load_extension(f'src.cogs.{filename[:-3]}')
print(f"{color_blush}Cog: {filename[:-3]} valid.")
except Exception:
print(f"{color_blush}Cog: {filename[:-3]} invalid.")```
delete the {color_blush}
dont. not worth it and you dont gain any functionality. if you want multiple profiles for whatever reason, just use webhooks. and even then the singular bot should work fine
class ConfirmButton(discord.ui.Button):
def __init__(self):
super().__init__(label="Confirm", style=discord.ButtonStyle.grey, custom_id="confirm")
async def confirm_callback(self, interaction: discord.Interaction):
options = [
discord.SelectOption(label="PayPal", description="Pay with PayPal"),
discord.SelectOption(label="Credit Card", description="Pay with Credit Card"),
discord.SelectOption(label="Bitcoin", description="Pay with Bitcoin"),
discord.SelectOption(label="Ethereum", description="Pay with Ethereum"),
discord.SelectOption(label="Apple Pay", description="Pay with Apple Pay"),
discord.SelectOption(label="Google Pay", description="Pay with Google Pay")
]
select = discord.ui.Select(placeholder="Select Payment Method", options=options)
select_view = discord.ui.View()
select_view.add_item(select)
embed = discord.Embed(
title='Select Payment Method',
description='Please select your payment method.',
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed, view=select_view)
class opened_ticket(discord.ui.View):
def __init__(self, ticket_channel):
super().__init__()
self.ticket_channel = ticket_channel
@discord.ui.button(label="Proceed", style=discord.ButtonStyle.grey, custom_id="proceed")
async def proceed_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = discord.Embed(
title='How much robux would you like to buy? (1/4)',
description="""
Example: **10,000**\nThe minimum order amount is **10,000** Robux
""",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed)
def check(msg):
return msg.author == interaction.user and msg.channel == interaction.channel and msg.content.isdigit()
while True:
try:
msg = await self.bot.wait_for('message', check=check, timeout=60.0)
except asyncio.TimeoutError:
return await interaction.followup.send("You took too long to respond.", ephemeral=True)
robux_amount = int(msg.content)
if robux_amount < 10000:
embed = discord.Embed(
title='Amount too low',
description='The minimum order amount is **10,000** Robux',
color=discord.Color.dark_red()
)
await interaction.followup.send(embed=embed)
else:
break
self.robux_amount = robux_amount
embed = discord.Embed(
title=f"Confirmation (2/4)",
description=f"Are you sure you want to buy **{self.robux_amount:,}** Robux?\nCurrent Rate: **$2.1 per 1,000**\nPrice in USD: **${(self.robux_amount / 1000) * 2.1:,.2f}**",
color=discord.Color.green()
)
confirm_view = discord.ui.View()
confirm_view.add_item(ConfirmButton())
await interaction.followup.send(embed=embed, view=confirm_view)
@discord.ui.button(label="Close", style=discord.ButtonStyle.grey, custom_id="close")
async def close_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.ticket_channel.delete()
del open_tickets[interaction.user.id]
my confirm button doesn't work
🤨
wsp
I take it you're not an authorized retailer
Whattt
cool badge btw, but what retailer lmao i was js asking for help?
I am making bot for someone else and i can't fix this error, by the way don't worry i bought from service before it is legit service i am not connected with any type of scams
that doesn't make it any less against the TOS, both roblox and discord's
oh really?
still bot isn't against tos it isn't the one breaking it so help me fix error 🙂
Is the "legit service" https://www.roblox.com/upgrades/robux
your point?
You may not use, acquire, or distribute Robux or Virtual Content except through the Services and except as expressly allowed by Roblox under these Roblox Terms. Any attempt to do so constitutes a violation of the Roblox Terms, will render the transaction void, and may result in the immediate suspension or termination of your Account and your license to use Robux or Virtual Content. Roblox does not recognize or take responsibility for third-party services that allow Users to sell, transfer, purchase, or otherwise use Robux or Virtual Content, and any such use by a User is a violation of the Roblox Terms
still the bot isnt against TOS so you should help them 🤷🏽♂️
im sure they would never do anything wrong
No, I need that for a big project
even if it hard to make
just give any source to learn from it
just use webhooks
its not easy and its not practical and its not worthwhile.
I dont want webhooks
why not?
I promise you its worth it for me
whats your use case for having multiple bots?
i promise you it most definitely isnt worth it for you
its a littile bit complicated
feel free to explain. i’ll listen
can you please just help me without explain pls 🙂
What makes you think this is true from reading the code for more than 15 seconds
if it doesnot annoy you
how did you not get the sarcasm from the message underneath 😭

acting like i endorse scams 😒
🙏 Anyone know of any resources talking about supporting multiple commands running at once?
Using like threads or some shit?
._. forgot to disable audio, anyways. Any idea on how to fix this? Future commands can't be ran unless the prior command completely finishes. Checks don't even come into play at all either
Ex.
/generate woman 20 -- generates a woman with 20 steps
then right after
/generate woman 60 -- Should say "You cannot generate an image with over 45 steps" but it'll just sit there and fail to respond until the previous command finishes.
sounds like you have blocking code
!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!
I have so much bs going on here lol I have no clue what needs to be asynced or awaited, I also have functions going on. And some things that cant be awaited like websockets
basically something in your code is causing it to pause everything else so it can run in peace before everything else can keep happening
I've went through and awaited and asynced everything I think is important, but now this is happening.
People can run the command and it generates for every command, but in the end only 1 gets uploaded..
Pretty sure I'm awaiting everything and asyncing everything important
awaiting something doesn't automatically make it async
async def fake_async_method():
time.sleep(100)
await fake_async_method()
will still block your event loop
Yeah I don't have any timers or anything going on
that's just an example
asyncio debug mode is a pretty good tool for locating anything that's blocking
solstice, its 30 minutes past midnight for me and i think ima fuck smth up if i try and answer this help post (#1236093064171356170). can you handle it? i dont want link to yell at me again
isn't it the same time for them lol
here it's 01:38 if that makes you feel better
i have a big day tomorrow as well. im so done for PepeHands
today or tmrw
im just gonna sleep. you handle it. i believe in you cat person man thingy
today 💀
go sleep then 
snuggling in bed rn 🥰🔥
boutta honk shoo in this bitch 🗣🗣
Br*tish...
@viscid hornet i need help with cogs:
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
try:
bot.load_extension(f'src.cogs.{filename[:-3]}')
print(f"Cog: {filename} cargado.")
except Exception:
print(f"Cog: {filename[:-3]} error.")
@bot.event
async def on_ready():
print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant"))
print(Fore.LIGHTWHITE_EX + f"({round(bot.latency * 1000, 2)}ms) | Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]")
try:
cursor.execute("SELECT 1")
result = cursor.fetchall()
if result:
print(Fore.LIGHTWHITE_EX + "--------------------------------")
print(Fore.LIGHTWHITE_EX + "[+] Conectado a la base de datos")
except sqlite3.Error:
print(Fore.LIGHTWHITE_EX + "-------------------------------------")
print(Fore.LIGHTWHITE_EX + "[-] No es posible establecer conexión")
await presence.start()
await load_cogs()```
on_ready fires repeatedly. You should not use it for things you want to do once
How can I improve it?: ```py
@tasks.loop(seconds=30)
async def presence():
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=f"{bot.command_prefix}help | {bot.command_prefix}invite"))
await asyncio.sleep(15)
await bot.change_presence(status=discord.Status.online, activity=discord.Activity(type=discord.ActivityType.watching, name=f"CPU: {psutil.cpu_percent():.2f}% | RAM: {psutil.virtual_memory().percent:.2f}%"))
await asyncio.sleep(15)
async def load_cogs():
for filename in os.listdir("src/cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"src.cogs.{filename[:-3]}")
@bot.event
async def on_ready():
print(Fore.LIGHTWHITE_EX + pyfiglet.figlet_format("Sew", font="slant"))
print(Fore.LIGHTWHITE_EX + f"({round(bot.latency * 1000, 2)}ms) | Prefix: [{bot.command_prefix}] Bot: [{bot.user.name}#{bot.user.discriminator}]")
try:
cursor.execute("SELECT 1")
result = cursor.fetchall()
if result:
print(Fore.LIGHTWHITE_EX + "--------------------------------")
print(Fore.LIGHTWHITE_EX + "[+] Conectado a la base de datos")
except sqlite3.Error:
print(Fore.LIGHTWHITE_EX + "-------------------------------------")
print(Fore.LIGHTWHITE_EX + "[-] No es posible establecer conexión")
await presence.start()```
2 questions,
https://paste.pythondiscord.com/VTNA
why am i only getting this error sometimes and not every time (lines >134)
any why is the elimination buggy? it doesnt always eliminate everyone who it should, and the game never ends with 0 players it does someone random
Oh no
I just started learning Python to make my own bot but I can't even get it to reply only to me 😭
I feel dumb
!paste lets see the code
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.
!code if its small
does this happen a while after you start your bot or immediately after
Fixed it
does that mention stuff actually work?
Yes it does
@commands.has_permissions(manage_roles=True)
@commands.hybrid_command()
async def role(self, ctx, Member: discord.Member, *, Role):
role = discord.utils.get(ctx.guild.roles, name=Role)
if role is None:
await ctx.send(f"Role '{Role}' not found.")
else:
if role not in Member.roles:
await Member.add_roles(role)
await ctx.send(f"Added **{role.name}** to **{Member.name}**")
else:
await Member.remove_roles(role)
await ctx.send(f"Removed **{role.name}** from **{Member.name}**")```
no the mention prefix
Yes it works
Can u help this tho
oh awesome
what do you need help with
Why does it adds and then removes it
It should just add it
it doesnt add and remove it
you forgot to indent the last line so it only gets run with the else part
Ah shit
its outside the if else check so it runs anyway
Ty
you should also consider renaming your args and looking into smth called “guard statements”
i only suggest renaming them because stuff like “discord.Role” exists and it starts to get really confusing if you have “Role” and “discord.Role”
again, guard statements are just to make your code cleaner and more readable
Ty I'll look into this

Guys is there any good updated youtube tutorials(advanced) on discord.py economy system?
If yes which one?
What's aim?
Like to interact with basic commands
Hmm
discord.py is good enough for this type of works...
Np
Someone pls help me
there aren't really videos on the sort, but i can explain what you have to do 🤷
uh, what would the role of discord.py be specifically in an "economy system"? if you're making something in a discord bot - the underlying concept doesnt change
have a database storing the information, when people do something - change the state, e.g. add monies 💰
the discord bot is just like, the ui for the system
the logic itself isnt tied to it
This might take a bit more effort, but you could look at source code for similar existing bots to see how they work
Is there a way to change channel permisions like for example a x role can send msgs in y channel I want to change something so that x role can't send messages in that channel only
@viscid hornet can u help

in code or in discord?
In code
Smtg like this you can redirect me to some docs
import aiosqlite
import tkinter as tk
import threading
class DatabaseUser:
def __init__(self):
self.conn = None
async def get_connection(self):
if self.conn is None:
self.conn = await aiosqlite.connect("nation.db")
await self.create_table()
return self.conn
async def create_table(self):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute('''CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
nation_id TEXT
)''')
await conn.commit()
async def add_user_nation(self, user_id, nation_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("INSERT INTO users (user_id, nation_id) VALUES (?, ?)", (user_id, nation_id))
await conn.commit()
async def is_user_registered(self, user_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("SELECT * FROM users WHERE user_id=?", (user_id,))
result = await cursor.fetchone()
return result is not None
async def remove_user(self, user_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("DELETE FROM users WHERE user_id=?", (user_id,))
await conn.commit()
async def get_user_nation_id(self, user_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("SELECT nation_id FROM users WHERE user_id=?", (user_id,))
result = await cursor.fetchone()
return result[0] if result else None```
@bot.command(
name="verify",
description="Register with the bot"
)
async def verify(ctx: commands.Context, nationid: str):
try:
# Check if the user is already registered
is_registered = await db_user.is_user_registered(ctx.author.id)
if is_registered:
embed = discord.Embed(
title="Registration Error",
description="You are already registered.",
color=0xff0000 # Red color
)
await ctx.send(embed=embed)
return
query= kit.query("nations", {"id": int(nationid)}, "discord")
result = query.get()
if not result or not result.nations:
embed = discord.Embed(
title="Registration Error",
description=f"Nation ID {nationid} not found.",
color=0xff0000 # Red color
)
await ctx.send(embed=embed)
return
discord_name = result.nations[0].discord
discord_username = ctx.author.name
if discord_username != discord_name:
embed = discord.Embed(
title="Registration Error",
description=f"Provided game username {discord_username} does not match {discord_name}",
color=0xff0000
)
await ctx.send(embed=embed)
return
await db_user.add_user_nation(ctx.author.id, nationid)
embed = discord.Embed(
title="Registration Successful",
description="Your nation is successfully registered.",
color=0x00ff00 # Green color
)
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(f"An error occurred: {e}")```
oh alr
tryna remember what it was holup
!d discord.Role.edit
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles) to do this.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
!d discord.Role.permissions
property permissions```
Returns the role’s permissions.
This error I get always
basically you do py YR: Role # short for "your role" YR.permissions.manage_messages = True # enables manage messages perms
what line is the error on?
You saying to me?
Me when no traceback so I can't trace the error :(
❌
It didn't gave that
sends error instead of raising it
"guys wheres the problem with the code"
because you sent the error instead of letting it be raised
.
await ctx.send(error) will only send the last line of the error
@bot.command(
name="verify",
description="Register with the bot"
)
async def verify(ctx: commands.Context, nationid: str):
try:
# Check if the user is already registered
is_registered = await db_user.is_user_registered(ctx.author.id)
if is_registered:
embed = discord.Embed(
title="Registration Error",
description="You are already registered.",
color=0xff0000 # Red color
)
await ctx.send(embed=embed)
return
query= kit.query("nations", {"id": int(nationid)}, "discord")
result = query.get()
if not result or not result.nations:
embed = discord.Embed(
title="Registration Error",
description=f"Nation ID {nationid} not found.",
color=0xff0000 # Red color
)
await ctx.send(embed=embed)
return
discord_name = result.nations[0].discord
discord_username = ctx.author.name
if discord_username != discord_name:
embed = discord.Embed(
title="Registration Error",
description=f"Provided game username {discord_username} does not match {discord_name}",
color=0xff0000
)
await ctx.send(embed=embed)
return
await db_user.add_user_nation(ctx.author.id, nationid)
embed = discord.Embed(
title="Registration Successful",
description="Your nation is successfully registered.",
color=0x00ff00 # Green color
)
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(f"An error occurred: {e}")```
we need the rest of it
yeah we saw the code
remove the try-except block and we can help you
I have to remove that from the code?
❌
⬆️
Ok
@viscid hornet
@naive briar you need other codes also?
I was looking away
Anyway, you don't need to use a context manager on an already connected connection:
conn = await aiosqlite.connect("...")
async with conn: # <--- should be removed
# do stuff
In db.py?
Anywhere
Since if you do, it will to connect wether it is already connected or not. Which is a weird choice to not do a check first 🫠
I meant
import aiosqlite
import tkinter as tk
import threading
class DatabaseUser:
def __init__(self):
self.conn = None
async def get_connection(self):
if self.conn is None:
self.conn = await aiosqlite.connect("nation.db")
await self.create_table()
return self.conn
async def create_table(self):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute('''CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
nation_id TEXT
)''')
await conn.commit()
async def add_user_nation(self, user_id, nation_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("INSERT INTO users (user_id, nation_id) VALUES (?, ?)", (user_id, nation_id))
await conn.commit()
async def is_user_registered(self, user_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("SELECT * FROM users WHERE user_id=?", (user_id,))
result = await cursor.fetchone()
return result is not None
async def remove_user(self, user_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("DELETE FROM users WHERE user_id=?", (user_id,))
await conn.commit()
Should I remove it from here?
async def get_user_nation_id(self, user_id):
conn = await self.get_connection()
async with conn:
cursor = await conn.cursor()
await cursor.execute("SELECT nation_id FROM users WHERE user_id=?", (user_id,))
result = await cursor.fetchone()
return result[0] if result else None```
Remove all of:
async with conn:
Ok
should be replacing them with “async with get_conn as conn:” imo
It's a weird design choice
import aiosqlite
class DatabaseUser:
def __init__(self):
self.conn = None # Connection will be established when needed
async def get_connection(self):
# Establish a connection to the database
if self.conn is None:
self.conn = await aiosqlite.connect("nation.db")
await self.create_table()
return self.conn
async def create_table(self):
conn = await self.get_connection() # Use await here
cursor = await conn.cursor()
await cursor.execute('''CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
nation_id TEXT
)''')
await conn.commit()
async def add_user_nation(self, user_id, nation_id):
conn = await self.get_connection() # Use await here
cursor = await conn.cursor()
await cursor.execute("INSERT INTO users (user_id, nation_id) VALUES (?, ?)", (user_id, nation_id))
await conn.commit()
async def is_user_registered(self, user_id):
conn = await self.get_connection() # Use await here
cursor = await conn.cursor()
await cursor.execute("SELECT * FROM users WHERE user_id=?", (user_id,))
result = await cursor.fetchone()
return result is not None
async def remove_user(self, user_id):
conn = await self.get_connection() # Use await here
cursor = await conn.cursor()
await cursor.execute("DELETE FROM users WHERE user_id=?", (user_id,))
await conn.commit()
async def get_user_nation_id(self, user_id):
conn = await self.get_connection() # Use await here
cursor = await conn.cursor()
await cursor.execute("SELECT nation_id FROM users WHERE user_id=?", (user_id,))
result = await cursor.fetchone()
return result[0] if result else None```
Ok