#discord-bots

1 messages · Page 360 of 1

tulip ice
#

ohhh how did i not see that

#

thank you

finite pagoda
#

``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``

tulip ice
#

i got this to work and tried it but if i change my mind on the genus it doesnt update the breed list

hushed galleon
tulip ice
#

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

hushed galleon
#

i meant typing something arbitrary into breed to refresh the autocompletion, but i guess that refreshes it too

tulip ice
#

that didnt work when i tried it

hushed galleon
#

weird, i thought the point of autocomplete callbacks were to provide different options as the user typed...

fathom tree
#

is there a way to get rid of this warning permanently, the code is correct works just fine.

hushed galleon
#

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

golden portal
hushed galleon
unkempt canyonBOT
#

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```
fathom tree
tulip ice
#

just to be certain there is no way to make it update?

hushed galleon
tulip ice
#

discord is irritating

tulip ice
#

there is surly way to force update it?

round jetty
#

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

spice seal
#

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

rugged shadow
spice seal
rugged shadow
#

what bot?

spice seal
#

Using code for doing it

rugged shadow
#

you don't need a bot just to filter swear words

spice seal
#

I don't wanna do it the old fashioned way

spice seal
rugged shadow
unkempt canyonBOT
#

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.
rugged shadow
#

in your trigger, put your swear word list in the keyword_filter

spice seal
#

How do I get words from a file called BadWords.txt and use it

rugged shadow
spice seal
#

As the trigger

spice seal
rugged shadow
spice seal
#

I don't want

#

I just need example

rugged shadow
#
trigger = AutoModTrigger(
    type=AutoModRuleTriggerType.keyword,
    keyword_filter=["fuck", "shit", "rust"],
)
#

then pass that in to create_automod_rule

spice seal
#

Ohk ok thats

rugged shadow
#

i'm assuming you already know how to read the words from the text file

spice seal
#

Ya ok

rugged shadow
#

just pass in the list to keyword_filter

spice seal
#

I will give updates here

#

Also how do I adjust the on_message to cope up with this?

rugged shadow
#

you don't do anything in on_message

#

just make a command the creates the rule and discord handles that for you

spice seal
#

Ohk thanks 👍

spice seal
gusty berry
#

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

gusty berry
#

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:
spice warren
#

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

gusty berry
# spice warren This comes back to when I told those two off several hours ago `Member.voice` i...
# 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?

spice warren
#

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

gusty berry
#

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

spice warren
gusty berry
#

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

shrewd apex
#

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

gusty berry
#

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

shrewd apex
#

online status is irrelevant to the no. of synced commands i believe

gusty berry
#

the problem is that he wont respond to any commands and the tree of / commands wont update even after kicking the bot

shrewd apex
#

thats weird

gusty berry
#

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

pale zenith
#

only a single guild= at a time

#

(anyway, that is kinda irrelevant)

spice warren
#

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

gusty berry
#

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

quick gust
#

how can I convert the permission's integer, eg- 35461652409665 to a list of permissions in plain text?

golden portal
turbid condor
#

!d discord.Permissions

unkempt canyonBOT
#

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).
golden portal
#

it supports iter which allows you to do dict and list

gusty berry
#

i got the bot playing audio using FFmpegPCMAudio. how can i stop all audio that the bot is playing?

spice warren
#

!d g discord.VoiceClient.stop

unkempt canyonBOT
spice warren
#

This method should help, since you already know how to get a VoiceClient

latent pier
#

How to add sticker in a guild?

wanton current
#

damn

latent pier
#

Damn

drifting arrow
#

the bots like na

latent pier
#

Like i didn't check😭

drifting arrow
wanton current
#

nah i was first

latent pier
#

Okay that helps but what about animated object turning into static 😭😭

drifting arrow
#

Dont trust this @wanton current guy. he's suspicious

latent pier
#

You both are like me and @viscid hornet
we compete too 🤣

drifting arrow
#

na i dont compete lol, im just bored.

wanton current
#

hi bored

drifting arrow
#

besides. my link was first and therefore use mine not that sus @wanton current 's

latent pier
#
        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

latent pier
drifting arrow
#

UP DOWN TURN AROUND

#

:D

#

actually I was thinking of a real song not this nonsense i just found this one first xD

latent pier
#

You forgetting the topic

drifting arrow
#

There is no topic. Only wiggles now.

wanton current
latent pier
wanton current
#

well, what is self.url?

latent pier
#

It was this sticker and it returned NomFoodStare NomFoodStare NomFoodStare

drifting arrow
wanton current
#

its a png

drifting arrow
#

yep

#

pngs are not animated.

latent pier
#

If we remove png it's none

#

It's just a preview

#

sticker_url returns same

drifting arrow
#

🤔

#

So the most two recent topics was someone making a voice bot and someone trying to make stickers.

latent pier
#

🤣🤣

#

Trying avoid animated stickers turning into png/static

#

Making a voice is still easier

#

@drifting arrow i checkef format type and it returned apng

wanton current
#

yeah it's an animated png

latent pier
#

But it changes when i get sticker url

#

Stupid discord

wanton current
latent pier
hushed galleon
brave galleon
#

thanks 🙂

brave galleon
#

Its my first time trying to use discord's slash commands

viscid hornet
#

@brave galleon

#

thats the link

brave galleon
#

Can you perhaps send me a link explaining how to do this?

#

Thanks

viscid hornet
brave galleon
#

xD

spice warren
#

Can you not ping reply please @viscid hornet

restive perch
#

Yeah sure sure no

#

This is against the ToS

latent pier
#

That's not a education purpose

left nova
latent pier
#

🤣

#

It's not as simple as that

left nova
#

i am jokin broski

restive perch
#

We aint joking too

plain pollen
#

we don't help with those, educational or not

left nova
distant fulcrum
#
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

distant fulcrum
#

Btw how to make it send a message that I wrote

#

Like I wrote $hello hi, then it should send hi

latent pier
#

It is not sending response?

#

Then how could you say 'it's working'

naive briar
#

!d discord.ext.commands.Bot <- docs

unkempt canyonBOT
#

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.
hushed galleon
#

#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

hushed galleon
# latent pier Wait, how would that work I've never used it before?

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()```

warped cave
latent pier
#

@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

hushed galleon
#

er, it looks like that just saves an individual frame instead of the entire animation

#

oh right, append_images= is there

latent pier
#

It's working but not after i downloaded it

#

I'll try yours

warped cave
#

@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

hushed galleon
#

do you know how to retrieve and compare the channel's name?

warped cave
#

no, i almost dont know anything about coding tbh

hushed galleon
#

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

latent pier
#

@hushed galleon okay i used it and worked but look

#

Why is it blinking from lower side

#

🤣

hushed galleon
#

and from that doc, you can see that TextChannel objects have a .name attribute, a string describing the name of the channel

hushed galleon
latent pier
#

This is original one

hushed galleon
#

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

warped cave
latent pier
#

Is it mandatory to save file or there could be any alternative like making a temporary instance of a file?

hushed galleon
#

ctx.channel.name == "kj" would be how you'd compare it to the literal string kj

hushed galleon
warped cave
latent pier
hushed galleon
#

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

warped cave
#

but where do i put ctx.channel.name == kj in the code

warped cave
#

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```

spice seal
wanton current
spice seal
#

Ohk

wanton current
#

!d discord.Guild

unkempt canyonBOT
#

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.
wanton current
#

You can see all of the attributes there

spice seal
wanton current
#

ctx.message

spice seal
#

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

sly hamlet
spice seal
wanton current
#

it's very hard to diagnose your problem with only the embed

rain hedge
#

better solution

#

use discord automod

wanton current
#

real

spice seal
#
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

rain hedge
#

im not so good with py myself

#

but shouldn't it be @bot.listen

wanton current
#

both work

spice seal
#

How to do it

rain hedge
spice seal
#

Pls help i can't upload code

wanton current
#

!paste

unkempt canyonBOT
#
Pasting large amounts of 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.

spice seal
#

viewpaste/TJMA

rain hedge
#

maybe click the link?

#

and past it

sly hamlet
hushed galleon
hushed galleon
sly hamlet
hushed galleon
#

i thought dpy didnt natively support voice recordings

warped cave
sly hamlet
#

I don't know. There's honestly not much documentation anywhere on how to do this

hushed galleon
# sly hamlet 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)

sly hamlet
#

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

spice seal
#

Hi my code is saying guild is not defined please help

#

How can I define it?

hushed galleon
# warped cave i feel dumb for not understand this xD

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!')```

hushed galleon
sly hamlet
#

Thank you very much appreciated. I'll give it a shot a bit later today

hushed galleon
#

you can get the guild from your message object via message.guild

rain hedge
#
@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?

warped cave
hushed galleon
rain hedge
#

so after.mention?

#

for example

hushed galleon
hushed galleon
rain hedge
#

thank you.

rain hedge
# hushed galleon mhm

where can I list a channel for it so send a mesasge to whenever the command is triggered?

hushed galleon
#

e.g. py channel = member.guild.get_channel(1234) if channel is not None: await channel.send("Something happened!")

warped cave
#

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!')```
hushed galleon
warped cave
#

the numbers you see is the channel id

#

but the rest of it should be okay ?

hushed galleon
#

is_in_channel() wasnt defined with any parameters, so you cant pass the channel ID in @is_in_channel("1234540499390431252")

warped cave
#

so the @is_in_channel("1234540499390431252") isnt working bc its not defined wiuth parameters

#

but how do i define it with a parameter

hushed galleon
#
def add(x, y):
    #   ^^^^ parameters (inputs)
    return x + y
    # ^^^^^^^^^^ return value (output)

>>> add(1, 2)
3```
warped cave
#

so at x i have to add my @is_in_channel ?

rain hedge
#

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.

warped cave
fast osprey
rain hedge
#

the role will represent a team

fast osprey
#

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?

spice seal
#

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 🙂

fast osprey
#
  1. make a list
  2. find some way to iterate through it. One possible way is to use itertools.cycle and save that somewhere, such as on an attribute on your bot
  3. when someone gets role X, get the next role from the round robin, give it to them with member.add_roles
viscid hornet
rain hedge
fast osprey
#

Similar to how you'd make it optional in any normal python function, by providing a default like = None

opal vortex
#

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)?

wanton current
#

nope

opal vortex
#

F

#

that would have totally optimized my code a bit more on the command...

fast osprey
#

Pretty much all you can do is have the select open the modal and pass its value(s) into it

latent pier
harsh orbit
#

how I can run multiple bots on 1 file?

fast osprey
#

It's inadvisable to do so, you're not really gaining anything functional in exchange for instability

harsh orbit
#

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

fast osprey
#

You can do that without running everything on a single python process

harsh orbit
#

how?

fast osprey
#

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

harsh orbit
#

can you give a simple example for this pls?

#

its use threading right?

harsh orbit
round jetty
#

Anyone got a simple python (replit) code for purging?

fast osprey
#

which becomes more unstable and fragile the more things you put on it

harsh orbit
#

so, what should I use

#

just give me some tips to start

fast osprey
#

I would recommend using a process manager

#

there are several available depending on what OS you're running on

viscid hornet
harsh orbit
round jetty
#

VS Code doesn’t have that key option anymore like replit does

viscid hornet
viscid hornet
fast osprey
round jetty
viscid hornet
#

can you elaborate

harsh orbit
round jetty
fast osprey
round jetty
# viscid hornet token?

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

harsh orbit
#

ok thx for help

viscid hornet
round jetty
viscid hornet
round jetty
#

In VS code at least when I tried couple months back and all videos said .env file no longer works

viscid hornet
#

give it a google search and tel me what happens

round jetty
round jetty
#

Appreciate the help tho big time

viscid hornet
fast osprey
#

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

viscid hornet
latent pier
pale zenith
#

.py and use the built-in import.

fast osprey
#

.wav of Morgan Freeman narrating your config

obsidian hill
#

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

fast osprey
#

An entire file for each command is pretty overkill. Long files aren't bad, poorly organized ones are

obsidian hill
#

so how can I organize it better??

fast osprey
#

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

obsidian hill
#

Well rn my bot.py is 400 lines with like 10 cmds

obsidian hill
#

now that it is I wanna switch to slash and format the code better

fast osprey
#

Well if you want slash commands, that's a separate migration and they have different behavior/features

#

Depends on which library you're using

obsidian hill
fast osprey
#

If using discord.py, the commands extension to declare your commands

fast osprey
#

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

obsidian hill
#

ohh yea ive seen that

#

But I dont understand, whats the ctx left: int, right: int etc

golden portal
fast osprey
#

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

obsidian hill
golden portal
#

nop, been waiting for it since forever, best thing you have is a mod's docs

spice warren
#

I'm just "a mod" now :(

golden portal
#

wdym what am i suppose to say, 'nerd'

sly hamlet
#
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
fast osprey
#

Your bot does not have a channel with that id cached

slate swan
#

can u fetcch the rules or guidelines channel from the community settings under the guild object?

obsidian hill
#

whats the member join event?

sick birch
obsidian hill
#

whats the code for it

sick birch
drifting arrow
quick gust
unkempt canyonBOT
#

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.
spice seal
#

Anyone has any way to have antispam and the spam work if the channel is as whitelisted_channel

viscid hornet
spice seal
viscid hornet
spice seal
#

Idk

viscid hornet
unkempt canyonBOT
#

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.
viscid hornet
#

also im half awake so not the time for questions 😂

spice seal
#

I can't understand how it works dm me if anyone can help in detail 🙂

viscid hornet
#

link you do this

spice warren
#

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

spice seal
viscid hornet
#

im gonna go now, bye 👋🏽

spice warren
spice seal
spice warren
#

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

spice warren
#

Okay, well, going from that documentation what parameters confused you

spice seal
spice warren
#

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.

fallow comet
#
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
spice warren
spice seal
spice warren
#

I already asked you to do something :)

quaint obsidian
#

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?

spice warren
#

(You have created a "bound method" meaning it requires a full class instance to call, hence the self argument)

quaint obsidian
#

what is a "bound method" ?

spice warren
#

A method which is bound to the class where it is defined

quaint obsidian
#

example?

spice warren
#
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()
quaint obsidian
#

I have it configManager = ConfigManager("configs/config", "configs/messages", "configs/warnings", "configs/commands", "configs/levels")

rugged shadow
#

you probably forgot self

rugged shadow
quick gust
spice warren
#

No I was mistaken upon reading their code

#

Their issue is something else, it looks like a difference between runtime and shown code.

quaint obsidian
#

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)

quaint obsidian
quaint obsidian
spice warren
#

There's a discrepancy between your error and your code, ensure your file is saved and everything necessary has been reloaded/restarted

quaint obsidian
#

I restarted pycharm and same error.

upbeat otter
upbeat otter
#

!d discord.ButtonStyle

unkempt canyonBOT
#

class discord.ButtonStyle```
Represents the style of the button component.

New in version 2.0.
upbeat otter
quaint obsidian
#

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.

upbeat otter
#

just try to get me on this one

#

what does this getButtonStyle return?

quaint obsidian
upbeat otter
naive briar
upbeat otter
#
button_style_obj = getattr(discord.ButtonStyle, getButtonStyle(msg, label1)
#

try this

#

@quaint obsidian ^^

quaint obsidian
#
    button_style_obj = getattr(discord.ButtonStyle, configManager.getButtonStyle(msg, label))
TypeError: ConfigManager.getButtonStyle() takes 2 positional arguments but 3 were given
spice warren
#

Please fully exit/close and restart your bot AFTER you ensure your file is saved and up to date

upbeat otter
#

Yeah ig maybe your editor is acting up

quaint obsidian
#

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

spice warren
#

Okay something is definitely fishy. Can you upload the whole file causing this issue here?

#

!paste

unkempt canyonBOT
#
Pasting large amounts of 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.

quaint obsidian
#

I know the code is like jungle, but I hope it is readable.

spice warren
#

Need the definition of ConfigManager too

quaint obsidian
#

@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.

quaint obsidian
slate swan
tawdry vector
#

How can u check if no message is sent in a channel in a minute?

gusty berry
#

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

naive briar
gusty berry
#

i tried that but i pasted the code before the client.run.

upbeat otter
gusty berry
spice seal
#

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?

gusty berry
#

nope

#

send the code snippet in here

upbeat otter
gusty berry
#

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

golden portal
#

better to put them in Bot.setup_hook

#

on_ready just triggers multiple time in a bot's life cycle

tawdry vector
tawdry vector
#
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

quaint obsidian
#

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
fast osprey
#

What is that file named?

slate swan
quaint obsidian
slate swan
#

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

latent pier
#

I think for loop has bad indentation

gusty berry
#

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

slate swan
#

cause .send_message does not return a Message object

#

you need to use this

#

!d discord.Interaction.original_response

unkempt canyonBOT
#

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.
latent pier
quaint obsidian
#

It worked. OMG. I don't know any it didn't worked with setattr

slate swan
quaint obsidian
#

Yes. You can add new functions or properties to the class.

slate swan
#

i mean technically it could have worked

#

but there literally is a method to add new components to view .add_item()

quaint obsidian
#

.add_item() adds a button, but I can't give that button a callback to be called when it is pressed.

slate swan
#

you can

#

by using a custom button

#

using a subclass

quaint obsidian
#

where?

slate swan
#

using a subclass

quaint obsidian
slate swan
#

what did you try then

quaint obsidian
#
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
slate swan
#

and what doesnt work in this

quaint obsidian
#

callback didn't run.

slate swan
#

how did you add this button to view

quaint obsidian
#

in the __init__ in my view I added with .add_item

slate swan
#

mkay well it must have worked

#

that uses Button subclassing

unkempt canyonBOT
#

examples/views/tic_tac_toe.py line 84

self.add_item(TicTacToeButton(x, y))```
slate swan
#

the buttons are added here

quaint obsidian
#

he uses discord.ui.Button I used discord.Button

#

maybe that is why.

slate swan
#

is discord.Button even a thing

quaint obsidian
#

yes

upbeat otter
#

no

#

!d discord.ui.Button

unkempt canyonBOT
#

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.
upbeat otter
#

this is a thing

wanton current
quaint obsidian
#

!d discord.Button

unkempt canyonBOT
#

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.
wanton current
#

it requires state

slate swan
#

ic

upbeat otter
quaint obsidian
#
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.

slate swan
#

you shouldnt be creating classes inside a function

quaint obsidian
#

then how can I do it?

slate swan
#

put the class outside

quaint obsidian
#

But I have n amount of buttons.

slate swan
#

if you need anything inside the class that you get from a function get it by __init__

quaint obsidian
#

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
slate swan
#
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()
slate swan
naive parcel
#

hey i have the same kinda issue with pyqt5

#

classes and functions

quaint obsidian
slate swan
#

if you dont care you can use your code if it works, just saying how things should be done

gusty berry
#

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

slate swan
unkempt canyonBOT
#

@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'}
gusty berry
#

i'll try to modify it a bit give me a min

slate swan
gusty berry
#

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?

wanton current
#

you can clone, delete

slate swan
#

yeah

spice warren
#

Full dot notation path to Class.method is needed

timber dragon
#

Oh

slate swan
#

!d discord.TextChannel.clone

unkempt canyonBOT
#

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.
slate swan
#

!d discord.abc.GuildChannel.clone or actually this since it applies to all channel types

unkempt canyonBOT
#

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.
quaint obsidian
# slate swan if you dont care you can use your code if it works, just saying how things shoul...

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.

slate swan
#

hmm may i ask why are you returning a class itself not an instance?

quaint obsidian
#

Because I have a function that later on calls it.

slate swan
#

mhm but you know you can create an instance before and then just pass it

quaint obsidian
#

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.

slate swan
#

mhm well thats fine

quaint obsidian
#

So is it good enough?

gusty berry
#

how can i pass which channel to close and delete to the TextChannel?

#

do i

quaint obsidian
#

take the channel id as arg.

slate swan
gusty berry
#

get the name from interaction and put it in the parentheses?

#

so TextChannel.get_channel.clone()?

slate swan
#

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

gusty berry
slate swan
#

try

gusty berry
#

i have with different code. i always get Unknown Integration

slate swan
#

then show that code

gusty berry
#
@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)
slate swan
#

.get_channel is not awaitable but .clone is

gusty berry
#

mb

slate swan
#

and instead of manual permission checks

#

you can just use .has_permissions check

#

!d discord.app_commands.checks.has_permissions

unkempt canyonBOT
#

@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...
gusty berry
#
channel = interaction.guild.get_channel(interaction.channel_id)
await channel.clone()

it still doesnt work

gusty berry
#

there is no error its just Unknown Integration

#

should i ctrl + r

#

and try $sync

slate swan
#

yea

gusty berry
#

it works now but when it copies the channel it moves it all the way down to the bottom of the text list

slate swan
#

well i guess you can then .edit new channel and change its position

gusty berry
#

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?

slate swan
#

more likely to a db

gusty berry
#

what is that?

slate swan
#

database

gusty berry
#

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?

slate swan
#

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

gusty berry
#

does linux support all of them or is that why sqlite3 exists?

slate swan
#

if you can have a file it means you can have it (yes it works on linux)

slim bloom
#

@viscid hornet

viscid hornet
slim bloom
viscid hornet
viscid hornet
slate swan
viscid hornet
slate swan
#

doubt it

copper flume
#
            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
pale zenith
#

Yeah you can't edit those

#

you need to edit the (uhh what is it called??) target?

#

yeah I think entry.target.

tawdry vector
#

@viscid hornet hi there

slim bloom
#

How can I activate the discord community in python discord?

slim bloom
fast osprey
#

This requires a human to agree to certain expectations from discord

copper flume
#

but target.before doesn't exit

#

exist*

pale zenith
copper flume
#

and I want to make the new role the older one again

#

so I'll need to use on_guild_role_update?

wanton current
dapper aurora
#

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

unkempt canyonBOT
#

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).
viscid hornet
#

this as well this

copper flume
pale zenith
quick gust
copper flume
pale zenith
#

before and after are the diff objects that show the changes made.

copper flume
pale zenith
#

you cannot edit a diff object

copper flume
#

alr ty

gusty berry
#

the code is in the link

#

the code does what it's suppose to but doesnt return a response and gives that error

fast osprey
#

unknown webhook tends to happen when you use followup or original_response methods before you send your initial response

boreal wolf
#

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 ?

GitHub

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

fast osprey
#

This probably wants a 2.0+ version of discord.py despite not denoting that in its requirements

boreal wolf
fast osprey
#

Upgrade it through pip

fiery girder
boreal wolf
fast osprey
#

Google is your friend here, upgrade pip package

safe mist
#

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?

fast osprey
#

You're not passing in a valid token

boreal wolf
fast osprey
#

How?

boreal wolf
fast osprey
#

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

boreal wolf
#

Should i try to reset the token ?

fast osprey
#

Worth a shot

boreal wolf
#

trying

#

That worked XD

#

But now help and setup commands not working

fiery girder
fast osprey
#

Probably worth contacting whoever owns that code if their code isn't working

safe mist
fiery girder
# safe mist thanks

and ppl can also type anything they want so choices are not a hard lock on which user can type

safe mist
#

since it would be more efficient if i could set default choices

fiery girder
#

you can probly put the choice you prefer at the start so it selects that first

fiery girder
gusty berry
#
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
long pecan
#

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?

hushed galleon
boreal wolf
hushed galleon
boreal wolf
wanton current
#

systemd is good

hushed galleon
#

shrug, use whatever process manager floats your boat

long pecan
hushed galleon
#

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

long pecan
#

compiling is just needed to get the code working right? after that it will run somewhat the same speed as a baby computer?

long pecan
hushed galleon
boreal wolf
slim bloom
#

what is best for a sqlite3 db .db or .sqlite3?

wanton current
#

no difference

hushed galleon
hushed galleon
boreal wolf
wanton current
#

well your guild table doens't exist

boreal wolf
wanton current
#

is there a schema

hushed galleon
#

eek, the maintainer only has a voice.db file in their repo

wanton current
#

rip

boreal wolf
hushed galleon
wanton current
#

2/10 on channel edits

boreal wolf
slate swallow
#

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

hushed galleon
# wanton current 2/10 on channel edits

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)

wanton current
#

when was this

hushed galleon
#

five minutes ago

#

with a 3* server bot

wanton current
hushed galleon
#

silent change then?

wanton current
#

¯_(ツ)_/¯

#

tbf it was 4 years ago so

idle lantern
#
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():```
#

oh

#

i see my problem

#

tysm

#

i feel like a dumbhead

wanton current
#

why are you checking type() instead of just message.author.name is not None

idle lantern
#

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

drifting arrow
#

i feel like there'd be a simpler way lol

drifting arrow
strong crow
drifting arrow
#

But if it's your own bot, and you have code that relies on the author, why wouldnt you set it?

hushed galleon
#

maybe its a message sent by something else?

drifting arrow
#

idk man, seems sus

idle lantern
craggy anvil
#
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 ![epain](https://cdn.discordapp.com/emojis/973001187869745152.webp?size=128 "epain")
idle lantern
#

its supposed to be within view i think not in the button super init

idle lantern
#

nvm

#

i havent read much about buttons yet

quaint obsidian
#

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?

fast osprey
#

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

quaint obsidian
#

that was just an example.

quaint obsidian
slate swan
unkempt canyonBOT
quaint obsidian
#

@slate swan will it work if the application commands are in cog?

slate swan
#

should

ivory falcon
#

is it possible to use discord.py and forks together?

sick birch
fast osprey
#

You won't get support from either even if it is possible

viscid hornet
viscid hornet
spice warren
#

No

ivory falcon
sick birch
ivory falcon
viscid hornet
#

its like trying to build a car with the parts of two cars stripped apart

sick birch
rain hedge
#
@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

unkempt canyonBOT
#

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).
upbeat mason
#

anyone here that can help?

wanton current
#

dont ask to ask

upbeat mason
#

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?

upbeat mason
quick gust
#

Are you loading the cog?

upbeat mason
# quick gust 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

viscid hornet
#

you need to await your load exts

upbeat mason
#

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

viscid hornet
upbeat mason
viscid hornet
topaz steppe
#

how I can control multiple discord bots from 1 bot
like restart them or change their tokens etc..

slim bloom
#

delete the {color_blush}

timber dragon
#

Won't work either

#

load_extenskon is async

#

Use setup_hook

viscid hornet
craggy anvil
#
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

fast osprey
#

🤨

craggy anvil
#

wsp

fast osprey
#

I take it you're not an authorized retailer

craggy anvil
#

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

fast osprey
#

that doesn't make it any less against the TOS, both roblox and discord's

craggy anvil
#

oh really?

#

still bot isn't against tos it isn't the one breaking it so help me fix error 🙂

wanton current
craggy anvil
#

your point?

fast osprey
#

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

viscid hornet
#

im sure they would never do anything wrong

topaz steppe
#

just give any source to learn from it

viscid hornet
#

its not easy and its not practical and its not worthwhile.

topaz steppe
#

I dont want webhooks

viscid hornet
topaz steppe
#

I promise you its worth it for me

viscid hornet
#

whats your use case for having multiple bots?

viscid hornet
topaz steppe
#

its a littile bit complicated

viscid hornet
topaz steppe
#

can you please just help me without explain pls 🙂

fast osprey
topaz steppe
viscid hornet
fast osprey
viscid hornet
chilly hare
#

🙏 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.

viscid hornet
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

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!
chilly hare
viscid hornet
chilly hare
#

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

fast osprey
#

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

chilly hare
#

Yeah I don't have any timers or anything going on

fast osprey
#

that's just an example

#

asyncio debug mode is a pretty good tool for locating anything that's blocking

chilly hare
#

How would one activate that?

#

Nvm I think I got it

viscid hornet
wanton current
#

isn't it the same time for them lol

viscid hornet
#

solstice is british?

#

wow

#

my day is ruined. thanks willi

wanton current
#

here it's 01:38 if that makes you feel better

viscid hornet
wanton current
#

today or tmrw

viscid hornet
#

im just gonna sleep. you handle it. i believe in you cat person man thingy

viscid hornet
wanton current
#

go sleep then fall

viscid hornet
#

boutta honk shoo in this bitch 🗣🗣

fast osprey
#

Br*tish...

slim bloom
#

@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()```
fast osprey
#

on_ready fires repeatedly. You should not use it for things you want to do once

slim bloom
# fast osprey 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()```
snow coral
#

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

naive briar
#

Oh no

cedar pebble
#

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

unkempt canyonBOT
#
Pasting large amounts of 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.

blazing beacon
#

!code if its small

unkempt canyonBOT
#
Formatting code on Discord

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

For long code samples, you can use our pastebin.

tawdry vector
sick birch
# tawdry vector

does this happen a while after you start your bot or immediately after

viscid hornet
tawdry vector
#
@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}**")```
viscid hornet
#

no the mention prefix

tawdry vector
viscid hornet
viscid hornet
tawdry vector
#

It should just add it

viscid hornet
#

you forgot to indent the last line so it only gets run with the else part

tawdry vector
#

Ah shit

viscid hornet
#

its outside the if else check so it runs anyway

tawdry vector
#

Ty

viscid hornet
# tawdry vector Ah shit

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

tawdry vector
#

Ty I'll look into this

latent pier
spice seal
#

Guys is there any good updated youtube tutorials(advanced) on discord.py economy system?
If yes which one?

neon olive
#

Which library is good for creative dis bot ?

#

Creating*

spice seal
neon olive
spice seal
#

Hmm
discord.py is good enough for this type of works...

neon olive
#

Okay

#

Ty!

spice seal
#

Np

viscid hornet
lyric sphinx
#

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

austere prairie
#

This might take a bit more effort, but you could look at source code for similar existing bots to see how they work

tawdry vector
#

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

tawdry vector
#

Smtg like this you can redirect me to some docs

distant fulcrum
#
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}")```
viscid hornet
#

tryna remember what it was holup

#

!d discord.Role.edit

unkempt canyonBOT
#

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...
viscid hornet
#

!d discord.Role.permissions

unkempt canyonBOT
distant fulcrum
viscid hornet
# unkempt canyon

basically you do py YR: Role # short for "your role" YR.permissions.manage_messages = True # enables manage messages perms

viscid hornet
naive briar
#

Me when no traceback so I can't trace the error :(

viscid hornet
distant fulcrum
viscid hornet
viscid hornet
distant fulcrum
viscid hornet
#

await ctx.send(error) will only send the last line of the error

distant fulcrum
#
@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}")```
viscid hornet
#

we need the rest of it

viscid hornet
#

remove the try-except block and we can help you

distant fulcrum
viscid hornet
distant fulcrum
#

@viscid hornet

viscid hornet
#

@naive briar you do this

#

idk what hes doing and im rushing to leave

distant fulcrum
#

@naive briar you need other codes also?

naive briar
#

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
naive briar
#

Anywhere

naive briar
distant fulcrum
# naive briar Anywhere

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```
naive briar
#

Remove all of:

async with conn:
distant fulcrum
#

Ok

viscid hornet
naive briar
#

It's a weird design choice

distant fulcrum
# naive briar Remove all of: ```py async with conn: ```
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```
naive briar
#

Ok