#discord-bots

1 messages · Page 278 of 1

sharp whale
#

thats why i used interaction.guild.get_role()

cloud dawn
#

But the role wasn't cached so it returned None.

sharp whale
#

to get the discord.Role object

cloud dawn
#

Get is for cached objects, where as fetch is for non cached objects, you will use the API to get the info.

#

But in this case you only need the .id attr so to fix this we simply make mod_role a snowflake.

#
overwrites ={
                    guild.default_role: discord.PermissionOverwrite(view_channel=False),
                    interaction.user: discord.PermissionOverwrite(view_channel=True),
                    discord.Object(config.mod_role): discord.PermissionOverwrite(view_channel=True)
                }
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

Changed in version 2.0: `role_id` parameter is now positional-only.
cloud dawn
#

Docs also say it returns an Optional Role object.

#

@slate swan I think I broke him

sharp whale
#

discord.Object worked

#

ty

#

@cloud dawn how do we send multiple embeds in one message?

slate swan
#

embeds kwarg

#

!d discord.TextChannel.send

unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
sharp whale
#

multiple embeds

slate swan
#

yeah

sharp whale
#

..(embed=[embed1, embed2])

#

not working

slate swan
#

no i said embeds

sharp whale
#

OH

warm jackal
#

how simple is it to make a bot for message proxying? like similar to tupperbox and such

cloud dawn
#

I'd say it's on the difficult side, definitely at least 2/3 years of programming experience if you code a lot.

frozen pivot
#

is there a channel to show off my python discord bot?

cloud dawn
#

Here, this is for any questions and discussions relating to Discord bot development.

frozen pivot
#

Anyone figure out how to subclass pycord or fork discord.py to grab a speaking event?

frozen pivot
cloud dawn
#

You can discuss the features of the bot, but do remember that we don't allow advertisement.

frozen pivot
#

er, maybe I should send the github only

cloud dawn
#

Code looks alright but I recommend not pushing any large commented out codes or a lot of comments in general in a final product.

frozen pivot
#

I'll just make a flag for the user to enable the gpt functions like live weather and scraping. That way I don't have it all commented out. Plus I need to clean the code a bit more

cloud dawn
#

I do like the concept, tough not sure why you have a js and a py bot.

frozen pivot
#

It has to do with that speaking event. Python discord libraries lack the ability to check if a user is speaking. now py libraries can definitely send and record voice to a voice channel. Thats actually what I hope to get some traction on here. I'm sure I can subclass the discord gateway classes to get the user speaking status

cloud dawn
frozen pivot
#

Im sure you can do it but none of the libraries I've found can handle it out of the box

#

I could use a message trigger, but that removes a lot of the ease of access by immediately transcribing and responding by voice itself

#

Some clever subclassing could do the job I think

#

I just haven't been able to get any opcodes

cloud dawn
frozen pivot
#

my current code uses pycord for the receiving audio and replying with audio . Just the speaking trigger is what I'm after. Best I can tell they haven't tackled that but I'm still looking through this

cloud dawn
#

I'd just recommend building your idea in js then.

frozen pivot
#

I'm working with a tutor to help me to do that. Though, I like python a lot 🙂

#

Thanks for you looking over this and doing some searching. I'll get there eventually

cloud dawn
#

@frozen pivot Did some more digging and apparently why not many libs have it is because it can break very easily and is undocumented thus against ToS.

frozen pivot
#

oof

cloud dawn
#

Not the ToS part that is stopping them but the part that it is undocumented.

frozen pivot
#

Yeah voice in general is poorly documented from what I've heard from pycord peeps

cloud dawn
#

Well yeah since it's a bit of a grey area since there are a lot of things regarding voice and receiving that can break ToS or even laws for that matter.

frozen pivot
#

It's a shame because it's a cool idea to speak back and forth. I want to make a project that also is an ai voice changer. For shy speakers with social anxiety they can use a surrogate to speak with the rest of the peeps

cloud dawn
#

You could also make a bot sit in each general channel of a server and have conversations between guilds lmao

frozen pivot
#

I might have to integrate it with a eula to cover things

#

Yep, voice bridge as well

shrewd apex
cloud dawn
frozen pivot
#

I hear ya

cloud dawn
#

You either break it or you don't. However the chances of Discord actually enforcing it is fairly low.

frozen pivot
#

This means an approved bot is unlikely 😄

#

I guess it'll always be a self hosted one

cloud dawn
#

I mean voice is pretty demanding if you could create an infrastructure that supports 100+ guilds with AI voice cover and GPT it would be very impressive and costly..

frozen pivot
#

They would add their own API tokens

#

Not a chance in the world I can get this quality without a large gpu cluster

#

I suspect discord will create their own bot for this purpose in a year or so

shrewd apex
#

clyde 2.0 coming soon

frozen pivot
#

Now using a free tts could scale. gTTS sounds crap though

#

I already use it when I don't want to eat my paycheck away

stark socket
#

is there any event on resume gateway connection that i can utilize?

sick birch
stark socket
#

on_resume():
call task

#

i think on resume exists so my problem is solved

slate swan
#

!d discord.on_resumed

unkempt canyonBOT
stark socket
#

resume or resumed? chat gpt said on resume xD

frozen pivot
#

that gpt meme gets stuff wrong constantly 😦

slate swan
#

Dont use gpt for coding 😵‍💫

#

It might seem cool but its more problem solving than just using google and docs

frozen pivot
#

It's cool to generate ideas, or lead you to places, but not for straight coding

stark socket
#

i mean its pretty handy, yeah but i just wanted to know if on reume event existed

#

in the first place

slate swan
#

That's the only place that will tell you

stark socket
frozen pivot
#

Should import the entire docs into GPT and then ask 😄

stark socket
#

or it can be done in other way

stark socket
slate swan
#

not like you have all events list with categories

frozen pivot
slate swan
stark socket
#

sure i prefer to just ask ; )

slate swan
#

ask gpt -> check if answer works -> if not ask here or go to docs so you are most likely loosing time

glad cradle
#

btw on_resumed is weird, I mean why not on_resume

vocal snow
#

probably because the dapi docs call the event "Resumed"

left mantle
#

does anyone know how to fix this error?

#

here's the code:

#
import discord
import os
import twitchio
from webserver import keep_alive
from twitchio.ext import commands

DISCORD_BOT_TOKEN = os.environ['TOKEN']
TWITCH_CLIENT_ID = os.environ['TWITCH_CLIENT_ID']
TWITCH_TOKEN = os.environ['TWITCH_OAUTH_TOKEN'] 
TWITCH_USERNAME = "graveyardztv"

discord_client = discord.Client(
    intents=discord.Intents.all(),
    command_prefix="!"
                                                             )
twitch_bot = commands.Bot(
    token=TWITCH_TOKEN,
    client_id=TWITCH_CLIENT_ID,
    nick=TWITCH_USERNAME,
    prefix='!',
    initial_channels=[TWITCH_USERNAME]
)

@discord_client.event
async def on_ready():
    print(f"We have logged in as {discord_client.user}")
    await twitch_bot.start()

@twitch_bot.event
async def event_ready():
    print(f"Twitch Bot Ready: {twitch_bot.nick}")

@twitch_bot.command(name='followers')
async def followers(ctx):
    twitch_user = await twitch_bot.get_users(TWITCH_USERNAME)
    if twitch_user:
        followers_count = twitch_user[0].follows.total
        await ctx.send(f"{Twitch_USERNAME} has {followers_count} Twitch followers!")

async def update_voice_channel_name(followers_count):
    for guild in discord_client.guilds:
        voice_channels = [channel for channel in guild.channels if isinstance(channel, discord.VoiceChannel)]
        for voice_channel in voice_channels:
            new_channel_name = f"{voice_channel.name} - Twitch Followers: {followers_count}"
            await voice_channel.edit(name=new_channel_name)

keep_alive()
discord_client.run(DISCORD_BOT_TOKEN)
cloud dawn
#

Well that's because this code is very old.

glad cradle
glad cradle
#

and I don't think that you can run both of them in the same process but well, try it

coral lintel
#

care to elaborate?

void whale
#

How do i download python on visual studios?3827pepebigeyes

coral lintel
#

variable path

#

I think you can just download vs code and python and after open a cmd and type python --version if it works then you can use it in vs code

#

@minor totem

cloud dawn
coral lintel
#

i used documation @cloud dawn

#

script kiddie

#

can someone give me a good answer?

cloud dawn
#

!d asyncio.ensure_future

unkempt canyonBOT
#

asyncio.ensure_future(obj, *, loop=None)```
Return:

• *obj* argument as is, if *obj* is a [`Future`](https://docs.python.org/3/library/asyncio-future.html#asyncio.Future "asyncio.Future"), a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task"), or a Future-like object ([`isfuture()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.isfuture "asyncio.isfuture") is used for the test.)

• a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") object wrapping *obj*, if *obj* is a coroutine ([`iscoroutine()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.iscoroutine "asyncio.iscoroutine") is used for the test); in this case the coroutine will be scheduled by `ensure_future()`.

• a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") object that would await on *obj*, if *obj* is an awaitable ([`inspect.isawaitable()`](https://docs.python.org/3/library/inspect.html#inspect.isawaitable "inspect.isawaitable") is used for the test.)

If *obj* is neither of the above a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") is raised...
coral lintel
#

yep

cloud dawn
#

Well is the obj passed a Future or a Task?

vale wing
#

I mean class initializers and run methods

#

Probably would want to gather() them too

#

Generally I wouldn't recommend this approach, instead make two bots and setup communication between them

devout drum
#

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

devout drum
grim robin
#

is it possible after a .defer() to send a modal?
I know you have to use .followup or .edit_original_response but I was hoping there is a workaround that

slate swan
#

anyone know why i cant use message.content on webhooks?

sick birch
#

Though you can follow up with a button or something that would open a modal

grim robin
hasty pike
#

member.default_avatar returning blank

sick birch
#

I'm assuming you meant display avatar?

#

!d discord.Member.display_avatar

unkempt canyonBOT
#

property display_avatar```
Returns the member’s display avatar.

For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.

New in version 2.0.
hasty pike
#

To separate user avatar and server avatar

sick birch
#

What do you want to display on the embed?

hasty pike
#

It's working fine with display avatar (giving me server avatar) but doesn't returning me default avatar

hasty pike
#

The one i have right now

sick birch
unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
sick birch
#

You need to handle when they don't have one set

hasty pike
#

Oh wait

#

default_avatar doesn't work ig

#

It's returning avatar with member.avatar

#

!d discord.Member.default_avatar

unkempt canyonBOT
#

property default_avatar```
Equivalent to [`User.default_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.default_avatar "discord.User.default_avatar")
hasty pike
#

Why put it there then if this doesn't work

twilit grotto
verbal flicker
#

i was making a discord bot with 3 python script files each having their own commands for a certain purpose but i ran into a problem where i try to run 1 of the commands in one of the scripts and it just gives me this discord.ext.commands.errors.CommandNotFound

turbid condor
verbal flicker
#

how do i load it

turbid condor
#

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

verbal flicker
turbid condor
#

Yes

tribal sleet
#

yo guys how I can make slash commands

#

And are slash commands same as application commands

hushed galleon
tribal sleet
#

But in first link to a message it doesn't import app_commands like that in second example code from GitHub

#

Why

#

And Please tell what is use of bot.tree.sync

hushed galleon
#

the first example doesnt import app_commands because it doesnt directly use it, on github it does in several places

#

and application commands must be registered directly with discord, otherwise your discord app wont show anything when you try looking for your command

tribal sleet
#

Hmm

left mantle
left mantle
naive briar
#

Send the new error then

vale wing
left mantle
#

i'll send the updated code aswell

#
import discord
import os
import twitchio
import asyncio
from webserver import keep_alive
from twitchio.ext import commands

DISCORD_BOT_TOKEN = os.environ['TOKEN']
TWITCH_CLIENT_ID = os.environ['TWITCH_CLIENT_ID']
TWITCH_TOKEN = os.environ['TWITCH_OAUTH_TOKEN'] 
TWITCH_USERNAME = "graveyardztv"

discord_client = discord.Client(
    intents=discord.Intents.all(),
    command_prefix="!"
                                                             )
twitch_bot = commands.Bot(
    token=TWITCH_TOKEN,
    client_id=TWITCH_CLIENT_ID,
    nick=TWITCH_USERNAME,
    prefix='!',
    initial_channels=[TWITCH_USERNAME]
)

twitchbot_event_loop = asyncio.new_event_loop()

@discord_client.event
async def on_ready():
    print(f"We have logged in as {discord_client.user}")
    await twitch_bot.start()

@twitch_bot.event
async def event_ready():
    print(f"Twitch Bot Ready: {twitch_bot.nick}")

@twitch_bot.command(name='followers')
async def followers(ctx):
    twitch_user = await twitch_bot.get_users(TWITCH_USERNAME)
    if twitch_user:
        followers_count = twitch_user[0].follows.total
        await ctx.send(f"{Twitch_USERNAME} has {followers_count} Twitch followers!")

asyncio.set_event_loop(twitchbot_event_loop)

async def update_voice_channel_name(followers_count):
    for guild in discord_client.guilds:
        voice_channels = [channel for channel in guild.channels if isinstance(channel, discord.VoiceChannel)]
        for voice_channel in voice_channels:
            new_channel_name = f"{voice_channel.name} - Twitch Followers: {followers_count}"
            await voice_channel.edit(name=new_channel_name)

twitchbot_event_loop.run_until_complete(update_voice_channel_name(followers_count))

keep_alive()
discord_client.run(DISCORD_BOT_TOKEN)
woeful mango
#

Hi there!
Q: is there any free services to run bot python to discord ?

left mantle
#

if you'd like it running 24/7 i can tell you how to do that aswell

woeful mango
#

yes

#

looking a ways to send website screenshots to discord via bot

left mantle
#

i don't think a bot can screenshot a website though i might be wrong

#

i can help you with the hosting of your bot

#

dm me

glad cradle
#

smh replit isn't good

cold sonnet
#

bro is advertising replit

left mantle
#

why'd you delete your messages?

glad cradle
#

because they weren't completely correct for his case

left mantle
#

ah okay

buoyant quail
normal jasper
slate swan
#

!d discord.Member.timeout

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 "(in Python v3.11)").

You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.

This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
normal jasper
#

await ctx.author.timeout(2) ?

slate swan
#

did you even open the docs page?

#

until (Optional[Union[datetime.timedelta, datetime.datetime]]) – If this is a datetime.timedelta then it represents the amount of time the member should be timed out for. If this is a datetime.datetime then it’s when the member’s timeout should expire. If None is passed then the timeout is removed. Note that the API only allows for timeouts up to 28 days.

#

it explains that clearly

#

Read that, understand and do it

normal jasper
slate swan
#

if you dont know how to work with datetime doesnt mean you can just pass random numbers and expect it to work

normal jasper
#

i think this is correct

slate swan
normal jasper
#

Also im getting this error idk why

#
Exception in thread Thread-2:
Traceback (most recent call last):
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\dns\win32util.py", line 48, in run
    self.info.domain = _config_domain(interface.DNSDomain)
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\dns\win32util.py", line 26, in _config_domain
    if domain.startswith('.'):
AttributeError: 'NoneType' object has no attribute 'startswith'
#

i have one task loop in my code is that causing this problem

slate swan
#

well looks like domain is None

normal jasper
#
import datetime
import discord
from colorama import Fore
from mcstatus import JavaServer
from discord.ext import commands,tasks
from config import TOKEN,GUILD_ID,SUGGESTION_CHANNEL_ID,BUG_REPORTS_CHANNEL_ID,SERVER_IP

global guild
client=discord.Bot(debug_guilds=[GUILD_ID],intents=discord.Intents.all())

@client.event
async def on_ready():
    global guild

    guild = client.get_guild(GUILD_ID)
    print(f"Logged into discord")

    change_status.start()
@client.event
async def on_message(message:discord.Message):
    if message.reference is not None:
        replied_to:discord.Message = await message.channel.fetch_message(message.reference.message_id)
        if replied_to.author.id in (823297858467397642):
            await message.author.timeout(datetime.timedelta(hours=2),reason="Replying to Staff")
    if message.channel.id in [SUGGESTION_CHANNEL_ID,BUG_REPORTS_CHANNEL_ID]:
        try:
            await message.add_reaction("👍")
            await message.add_reaction("👎")
        except:
            pass


@tasks.loop(seconds=10)
async def change_status():
    try:
        fserver = JavaServer.lookup(SERVER_IP)
        fstatus = fserver.status()
        await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f'{fstatus.players.online} Players!'))
        print(f"[Debug] Pinged! | Players : {fstatus.players.online}")
    except Exception as ex:
        await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="Server Offline!"))

if __name__ == "__main__":
    client.run(TOKEN)
normal jasper
buoyant quail
normal jasper
#

im using mctools module to get the number of players online in a minecraft server

normal jasper
slate swan
#

well you are not starting the task now

normal jasper
#

but it shouldn't give anny error since the whole task loop is in a try except block

normal jasper
slate swan
normal jasper
slate swan
buoyant quail
unkempt canyonBOT
#

@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Exception in thread Thread-1 (f):
002 | Traceback (most recent call last):
003 |   File "/usr/local/lib/python3.11/threading.py", line 1038, in _bootstrap_inner
004 |     self.run()
005 |   File "/usr/local/lib/python3.11/threading.py", line 975, in run
006 |     self._target(*self._args, **self._kwargs)
007 |   File "/home/main.py", line 4, in f
008 |     1 / 0
009 |     ~~^~~
010 | ZeroDivisionError: division by zero
cold sonnet
#

that's actually

#

an insane amount of api calls

#

I mean those features do require those api calls

hasty coral
#

I have an issue with a command that works usually but doesnt work as a slash command. (1. The error -- 2. The code)

( 1 )

- Traceback (most recent call last):
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'addemoji' raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes

( 2 )

@bot.tree.command(name="addemoji", description="Add an emoji")
@commands.has_permissions(manage_expressions=True)
@app_commands.describe(name = "name")
@app_commands.describe(source = "source")
async def addemoji(ctx: discord.Interaction, name: str, source: str):
    try:
        emoji = await ctx.guild.create_custom_emoji(name=name, image=source)
        await ctx.response.send_message(f"Emoji '{name}' added: {emoji}")
    except discord.Forbidden:
        await ctx.response.send_message("I don't have permission to add emojis.")
    except discord.HTTPException:
        await ctx.response.send_message("Failed to add the emoji. Please make sure the URL is valid and the image is in the correct format.")
hasty pike
#

ImportError: cannot import name 'Enum' from 'discord' (unknown location)

slate swan
#

you cant import Enum from discord

hasty pike
slate swan
hasty pike
#

You guys call it against TOS

#

So i didn't

slate swan
#

wavelink 🧐

hasty pike
#

It's 2.6

#

I migrated just now and it stopped working

#

🤡

slate swan
#

all i can help you is check your libraries installed but i didnt tell you that 🤫

livid hedge
#

Hello, I recently started to code bots for more than one server at the time. I noticed that the same code is being executed for all the servers. Is there a way to create something like multiple instances for each server?

normal jasper
#

im getting this error

slate swan
#

but seems like you are trying to use isoformat method on it

normal jasper
# slate swan but seems like you are trying to use `isoformat` method on it
Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\imac\PycharmProjects\NeverLand\main.py", line 26, in on_message
    await message.author.timeout(timedelta,reason="Replying to Staff")
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 854, in timeout
    await self.edit(communication_disabled_until=until, reason=reason)
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\member.py", line 823, in edit
    ] = communication_disabled_until.isoformat()
AttributeError: 'datetime.timedelta' object has no attribute 'isoformat'
#
@client.event
async def on_message(message:discord.Message):
    if message.reference is not None:
        replied_to:discord.Message = await message.channel.fetch_message(message.reference.message_id)
        if replied_to.author.id in (823297858467397642,764417255018594314):

            timedelta=  datetime.timedelta(hours=2)
            await message.author.timeout(timedelta,reason="Replying to Staff")
            await message.channel.send(f"{message.author.name} به دلیل ریپلای به {replied_to.author.name} 2 ساعت تایم اوت 
normal jasper
slate swan
#

ah then it explains it all

#

in pycord you cant use timedelta

#

it can be datetime.datetime only

#

but

#

there is other method that accepts timedelta

#

check out this method ^ @normal jasper

normal jasper
#

❤️

dark heath
#

Hello, I would like to know how I can make that when the timer ends a message is sent to say that the vote is finished in my code below I have an error at the end of the timer which is :

2023-07-30 17:24:04 ERROR    discord.ui.modal Ignoring exception in modal <my_modal timeout=None children=3>:
Traceback (most recent call last):
  File "C:\Python311\Lib\site-packages\discord\ui\modal.py", line 188, in _scheduled_task
    await self.on_submit(interaction)
  File "C:\Users\Shadow\Desktop\Discord Bot\Cutie\BFS - Blox Fruit Service\Test_bot\cogs\vote.py", line 73, in on_submit
    await interaction.response.send_message(content="Voting has ended!", ephemeral=True)
  File "C:\Python311\Lib\site-packages\discord\interactions.py", line 774, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before

Here is the code for my vote.py
Thanks in advance to those who will take the time to help me and I apologize in advance for the inconvenience.

https://paste.pythondiscord.com/QOMA

turbid condor
#

Whereas it can only be used once

#

After that u have to use interaction.followup

#

!d discord.Interaction.followup

unkempt canyonBOT
turbid condor
#

Or the interaction has already completed

dark heath
#

So the message that returns that "the vote is over" to do this I must do interaction.followup("the vote is over")?

turbid condor
#

interaction.followup.send(...)

dark heath
#

Ohw .send okey I'll try that!

#

It works, thank you very much! But I have another question, if you don't mind?

turbid condor
#

Fire away

dark heath
#

In my voting embed I have the % user reaction percentage for each possible answer. The problem is that it works every other time but I can't figure out why and I have no errors. AMpotatosweat

turbid condor
#

Can u elaborate it I can't understand what u mean

dark heath
#

This is the embed that my voting command returns when I click on a reaction it should update the % for example it should put me 100% for option 2 but it only works every other time.

turbid condor
#

You mean it doesn't show the percentage?

naive briar
#

You mean the bot is not processing the reaction when it should?

dark heath
#

exactly when I click on the reaction the percentage should increase but it doesn't all the time. Excuse me for my poor English, I don't speak basic English. 😅

naive briar
#

Can you show the code responsible for handling it?

dark heath
#
async def update_embed():
            nonlocal timer, votes
            total_votes = sum(votes.values())
            updated_embed = discord.Embed(title=self.title, description=f'{self.texte}: \n\n{self.responses}', color=0x000cff)
            updated_embed.set_thumbnail(url="https://media.discordapp.net/attachments/1130037768928628807/1130440607932874784/standard_1.gif")
            updated_embed.set_footer(text=f"Voting time left: {timer}")

            if self.responses.default is not None:
                response_lines = self.responses.default.splitlines()
            else:
                response_lines = []

            for reaction, count in votes.items():
                percentage = count / total_votes * 100 if total_votes > 0 else 0
                option_text = response_lines[int(reaction[0]) - 1] if response_lines else f"Option {reaction[0]}"
                updated_embed.add_field(name=f"{reaction} {option_text}", value=f"{count} ({percentage:.2f}%)", inline=False)

            await msg.edit(embed=updated_embed)```
#

Just this code, or did you want the entire file code?

naive briar
#

Why nonlocal pithink

#

Never seen it being used before

verbal flicker
#
import json
from discord import Webhook
import aiohttp


with open('config/config.json', 'r') as config_file:
    tk = json.load(config_file)
    webh = tk['webhook']




async def logged():
    async with aiohttp.ClientSession()as f:
        webhook = Webhook.from_url(url=webh, session=f)
        await webhook.send('hello world')

idk why i just get this error "Command raised an exception: TypeError: from_url() got an unexpected keyword argument 'session'"

dark heath
#

To access and modify timer and votes variables

naive briar
dark heath
#
class my_modal(ui.Modal, title="Vote"):
    texte = ui.TextInput(label="Texte", style=discord.TextStyle.short, required=True)
    number = ui.TextInput(label="Number of responses", style=discord.TextStyle.short, required=True)
    responses = ui.TextInput(label="responses", style=discord.TextStyle.paragraph, required=True, default="")

    def __init__(self):
        super().__init__()
        self.vote_finished = False

    async def on_submit(self, interaction: Interaction):
        timer = 60
        reactions = []
        numbers = int(self.number.value)
        for i in range(1, numbers + 1):
            reactions.append(str(i) + "️⃣")

        embed = discord.Embed(title=self.title, description=f'{self.texte}: \n\n{self.responses.default}', color=0x000cff)
        embed.set_thumbnail(url="https://media.discordapp.net/attachments/1130037768928628807/1130440607932874784/standard_1.gif")
        msg = await interaction.channel.send(embed=embed)
        await interaction.response.send_message(content="Vote sent successfully", ephemeral=True)
        for reaction in reactions:
            await msg.add_reaction(reaction)
        start_time = time.time()
        votes = {reaction: 0 for reaction in reactions}

        def check(interaction: Interaction, user: discord.User):
            return interaction.user.id == user.id and time.time() - start_time < 60

        async def update_embed():
            nonlocal timer, votes
            total_votes = sum(votes.values())
            updated_embed = discord.Embed(title=self.title, description=f'{self.texte}: \n\n{self.responses}', color=0x000cff)
            updated_embed.set_thumbnail(url="https://media.discordapp.net/attachments/1130037768928628807/1130440607932874784/standard_1.gif")
            updated_embed.set_footer(text=f"Voting time left: {timer}")

            if self.responses.default is not None:
                response_lines = self.responses.default.splitlines()
            else:
                response_lines = []

            for reaction, count in votes.items():
                percentage = count / total_votes * 100 if total_votes > 0 else 0
                option_text = response_lines[int(reaction[0]) - 1] if response_lines else f"Option {reaction[0]}"
                updated_embed.add_field(name=f"{reaction} {option_text}", value=f"{count} ({percentage:.2f}%)", inline=False)

            await msg.edit(embed=updated_embed)

        while timer > 0 and not self.vote_finished:
            await asyncio.sleep(1)
            timer -= 1
            await update_embed()

            try:
                reaction, user = await interaction.client.wait_for('reaction_add', timeout=0.5)
                if reaction.emoji in reactions and check(interaction, user):
                    votes[reaction.emoji] += 1
            except asyncio.TimeoutError:
                pass

        # Voting is finished, send the "Voting has ended!" message
        if not self.vote_finished:
            self.vote_finished = True
            await interaction.followup.send(content="Voting has ended!")
            await update_embed()
naive briar
#

!d discord.Webhook.from_url

unkempt canyonBOT
#

classmethod from_url(url, *, session=..., client=..., bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") from a webhook URL.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
verbal flicker
#

im just following the steps

naive briar
#

Are you sure that it's really discord.py? Because I don't think so

verbal flicker
#

yeah im pretty sure it is

hushed galleon
dark heath
verbal flicker
naive briar
naive briar
dark heath
naive briar
#

!d discord.Reaction.emoji

unkempt canyonBOT
naive briar
#

I think if you compare this to a string the results will always be False

#

I'd recommend you to convert it to a string before comparing

dark heath
#

Should I convert reaction.emoji to string before comparing it to reactions and check(interaction, user)?

frosty beacon
#

what are the standard practices that i should follow to make embeds on runtime??

valid elbow
#

This is a bit off topic but figured people here might know.

I want to make a bot for google chat. I have not tried anything yet but I see there is a chat api from google. Anyone have experience in this area that can recommend a direction ?

livid hedge
#

Hello, I recently started to code bots for more than one server at the time. I noticed that the same code is being executed for all the servers. Is there a way to create something like multiple instances for each server?

#

I could create them manually but is there a procedure that I should follow?

slate swan
#

You can use a database so that the bot may be configured on a per-server basis, but you don't need to be running an instance of the bot for each individual server

gilded depot
#

guys

#

I really need help with something

#

@gloomy hound (it does say ping to reply)

gloomy hound
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied timeout to @gilded depot until <t:1690737144:f> (10 minutes) (reason: mentions spam - sent 7 mentions).

The <@&831776746206265384> have been alerted for review.

gloomy hound
#

rip

#

I apologize

thorn parrot
#

what

#

who pinged me

gloomy hound
thorn parrot
#

jesus christ

acoustic parcel
#

Wat

thorn parrot
#

he pinged anyone's name that has ping in it

#

what a chad

odd minnow
#

@thorn parrot

#

this is @gilded depot 's alt account

thorn parrot
#

blud

#

you pinged me again

odd minnow
#

ye

#

sorryi

thorn parrot
#

blocked dc

odd minnow
odd minnow
thorn parrot
#

or imma just leave this server

odd minnow
#

ok

#

that's your call

plain pollen
#

@odd minnow you got muted by the bot for a reason, jumping onto a second account to evade it really isn't what you should've done

odd minnow
#

ive been tackling this piece of code for days which ironically enough is a discord bot

#

so Im not gonna let something which is similar to what im making stop me

#

from helping its own kind

gilded depot
#

so ye

#

I think my alt accoun wrapped it up pretty nicely

#

?

gloomy hound
#

yes

#

hi

buoyant quail
#

the guy just wrote the channel name in all channels

slate swan
#

totally normal you dont do that stuff?

buoyant quail
#

ye, twice a week

serene egret
#

how I can make it work after the reset?

@client.command()
async def suggest(ctx, *, reason):
    count1 = 0
    count2 = 0
    interacted_users = []  

    async def button_callback1(interaction):
        nonlocal count1
        user_id = interaction.user.id
        if user_id not in interacted_users:
            count1 += 1
            interacted_users.append(user_id) 
            print(f"Good Suggestion Count: {count1}")
            embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")
            await interaction.message.edit(embed=embed)
            await interaction.response.send_message("Thank you for your vote!", ephemeral=True)
        else:
            await interaction.response.send_message("You have already voted.",ephemeral=True)

    async def button_callback2(interaction):
        nonlocal count2
        user_id = interaction.user.id
        if user_id not in interacted_users:
            count2 += 1
            interacted_users.append(user_id)  
            print(f"Bad Suggestion Count: {count2}")
            embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")
            await interaction.message.edit(embed=embed)
            await interaction.response.send_message("Thank you for your vote!", ephemeral=True)
        else:
            await interaction.response.send_message("You have already voted.",ephemeral=True)

    button = discord.ui.Button(style=discord.ButtonStyle.green, label="Good Suggestion", custom_id="Good_Suggestion")
    button.callback = button_callback1

    button2 = discord.ui.Button(style=discord.ButtonStyle.red, label="Bad Suggestion", custom_id="Bad_Suggestion")
    button2.callback = button_callback2

    embed = discord.Embed(color=ctx.message.author.color, timestamp=ctx.message.created_at)
    embed.set_author(name=f"{ctx.message.author}({ctx.message.author.id})", icon_url=ctx.message.author.avatar)
    embed.add_field(name='Suggestion:', value=f"{reason}")
    embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")

    view = discord.ui.View()
    view.add_item(button)
    view.add_item(button2)

    message = await ctx.send(embed=embed, view=view)
    embed.set_footer(text=f"Likes: {count1} | Dislikes: {count2}")
    await message.edit(embed=embed)
slate swan
#

do you mean you want the buttons work after reset?

serene egret
#

yes

buoyant quail
#

Store the data in database and load from it instead of memory

#

And make them persistent after that

slate swan
serene egret
#

ok

gilded depot
high spade
#

Hey I have a really dumb question. I am trying to find a good way to do speech recognition in real time in a discord voice channel. I am having trouble though and was wondering if any one has a code snippet or something like that to point me in the right direction

vale wing
#

Iirc nextcord does tho

high spade
high spade
vale wing
vale wing
high spade
#

Ty man. Is it ok if I dm for any questions. Trying to make something fun for some friends and possible YouTube video. But i want to spend some hours messing with it before i ask any dumb questions

glad cradle
#

pycord implements it

gilded depot
upbeat gust
slate swan
hushed galleon
#

does nextcord actually implement it? last i checked i couldnt find any mention of it in their docs
also the issue for it seems to be open: nextcord/nextcord#54

lament depotBOT
slate swan
#

i want to add tries to this command

@bot.command()
async def play(ctx, n):
    tries = 0
    number = str(random.randint(1,int(n)))
    await ctx.send(f"guess the number between 1 and  {n}")
    def check(msg=discord.Message) -> True:
        return msg.content == number and tries == 5
    try:
        p = await bot.wait_for('message', check=check)
        if p.content == number:
            await ctx.send(f"you win the number was {number}")
        else:
            tries += 1
    except asyncio.TimeoutError:
        await ctx.send(f"time over the number was {number} and you did x tries")```
any ideas?
upbeat gust
slate swan
shrewd parrot
#
intents = discord.Intents.all()
bot = commands.Bot(command_prefix = '.', intents=intents,  help_command=None)
prefix = '.'

class Bot(BotBase):

    async def process_commands(self,origin):
        ctx = await self.get_context(origin, cls=Context)
      
        if ctx.command is not None:
          await self.invoke(ctx)      

     async def on_message(self, message):
        await self.process_commands(message)

bot = Bot()

ctx.command returns None, so commands for my discord bot don't get processed- any ideas on why this might be happening?

exotic island
vocal snow
hushed galleon
#

^ didnt think of that but good point
though why are you inheriting BotBase instead of commands.Bot? you're missing a lot of Client functionality with it

drifting arrow
#

Using the discord API, what would be the best way to query my discord server to get how many are in my server?

hushed galleon
shrewd parrot
#

should I switch to commands.Bot?

vocal snow
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

shrewd parrot
vocal snow
#

ah didnt see that mb

shrewd parrot
#

all good I added it later

#

ctx returns data but

#

ctx.command is None

buoyant quail
#

Hmm, but actually the source code has kinda the same thing

#

Maybe something wrong with your context class?

shrewd parrot
#

hmm good thinking

#

so my code is ran through cogs

#

by context class do you mean classes I have under cogs?

buoyant quail
shrewd parrot
#

ohhh

#

I can delete it but that's the default parameter for cls

#

it's not a custom context class

buoyant quail
#

Hmm, didn't you get an error in this code? I guess i see the problem, but you should get an error with that

Ahh, understood
There is no error because BotBase is subclassed, not client or bot

shrewd parrot
#

I didn't get any errors

buoyant quail
#

First your bot has prefixes and intents

#

But then you replace it with empty one

shrewd parrot
#

I didn't paste my full code

#

I dunno man'

shrewd parrot
exotic island
vocal snow
#

not to your own Bot instance

#

and then you end up overriding the commands.Bot instance anyways so it is never used

tall temple
#

hey guys

#

i think imma getting trashed but please how can i create a discord bot with each command in a single file and execute them all with a main ?

naive swan
#

Trying to write a command that will return an image of fox from some-random-api and found this piece of code online, but for some reason it doesn't work.

#

The console points at line 34, but i dont see anything wrong there

#

feel free to ping me, though

naive briar
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 2, in <module>
003 |     json.loads("")
004 |   File "/usr/local/lib/python3.11/json/__init__.py", line 346, in loads
005 |     return _default_decoder.decode(s)
006 |            ^^^^^^^^^^^^^^^^^^^^^^^^^^
007 |   File "/usr/local/lib/python3.11/json/decoder.py", line 337, in decode
008 |     obj, end = self.raw_decode(s, idx=_w(s, 0).end())
009 |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
010 |   File "/usr/local/lib/python3.11/json/decoder.py", line 355, in raw_decode
011 |     raise JSONDecodeError("Expecting value", s, err.value) from None
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/L5XUFJJ6FOUXTIKGHWZLNOXTMA

naive briar
#

The response.text is probably returning an empty string

#

!blocking (this also)

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!

gilded depot
#

Guys

#

I really need help with something

#

and I apologise for the disrespect

#

but I really would appreciate help 🙂

tall temple
#

hey guys
i think imma getting trashed but please how can i create a discord bot with each command in a single file and execute them all with a main ?

gilded depot
#

i can help

#

if u send ur code

finite geyser
grim robin
#

is there a way to check if a specific command has been synced with a server?

finite geyser
#

bot.tree.sync() return list of all the synced commands @grim robin

naive swan
cloud dawn
naive swan
#

i think i need to somehow specify that i need the "image" from here

grim robin
finite geyser
cloud dawn
#

@grim robin Do know that this is a bit of a "grey" area meaning it isn't "really" against ToS but isn't a supported method of doing it. Meaning Discord likely doesn't want you to.

#

But then again, Discord could've added a simple event imo

finite geyser
cloud dawn
#

!d dict.get

unkempt canyonBOT
#

get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
naive swan
finite geyser
finite geyser
naive swan
#
resp = requests.get('https://some-random-api.ml/img/fox')  
    data = resp.json()
    imageurl = data["image"]
    embed1 = discord.Embed(color=0xff9900, title='Random Fox')
#

oh, ignore the embed thingy

finite geyser
#

it should work

jade flare
#

so i tried adding chatgpt to my dc bot but when i try to execute the command it tellss me i didnt provide an api key even though i did. can someone tell me what i did wrong?

naive swan
#

again, i dunno what's wrong

finite geyser
finite geyser
jade flare
finite geyser
naive swan
finite geyser
#

hmm

naive swan
#

the full command code, though i dont think it will make any difference

@client.command()
async def fox(ctx):
    resp = requests.get('https://some-random-api.ml/img/fox')  
    data = resp.json()
    imageurl = data["image"]
    embed1 = discord.Embed(color=0xff9900, title='Random Fox')  
    embed1.set_image(text=imageurl)  
    await ctx.send(embed=embed1)
finite geyser
#

well many ways to do same work

naive swan
#

yup, this one works, while the other one doesn't. broken api ig?

vale wing
cloud dawn
#

As long as you ensure that the running program won't crash/stop.

vale wing
naive swan
vale wing
jade flare
finite geyser
exotic island
#

hi guys i need to set embed footer with interaction.user.joined_at , what should i write after interaction.user.joined_at

vale wing
#

You sure you need footer and not timestamp

exotic island
#

oh

vale wing
#

Timestamp is set in constructor

#

embed = discord.Embed(timestamp=interaction.user.joined_at)

#

There probably is a method but I forgor

#

Okay there's no

#

Only attr setting or constructor

exotic island
#

yeah ty it works

cloud dawn
#

Sounds to me like you're on a laptop.

ember mango
cloud dawn
#

And that you are using the trackpad.

velvet sierra
#

something wrong with the discord? my bot are just sending the same message twice

cloud dawn
#

Check task manager to be certain.

turbid condor
velvet sierra
#

looks like i was stopping and starting the bot so fast that it make this thing happen

gilded depot
#

please help here

slate swan
#

How about you wait there

#

Wondering how its related to JavaScript or HTML

gilded depot
#

please man

#

I actually really need help

#

2 days since i first started asking

#

i acc need help

vocal snow
#

please send your code and traceback

gilded depot
#

thats the prroblem

#

there is no error.

#

it just doesnt workin the way I inntended t to

vocal snow
#

ok, then send your code and explain what's going wrong

gilded depot
#

basically

#
# Randomly choose a member from all_members list
            random_member = random.choice(all_members)
 
            # Create a dictionary to store permissions for all members
            member_permissions = {}
            for member in channel.members:
                if member == random_member:
                    # Random member has send_messages permission
                    member_permissions[member] = discord.PermissionOverwrite(read_messages=True, send_messages=True)
                else:
                    # All other members have send_messages permission disabled
                    member_permissions[member] = discord.PermissionOverwrite(read_messages=True, send_messages=False)
#

this main bit is causing errors

naive briar
#

You just said there is no error

gilded depot
#

When I click the buttton, it should get a random memebr from the list i made of all the members in the command the user would send, and then set everyone but that random members permissions to send messages as FALSE. so the random memnber should still have their perms to send messages as TRUE. When I run it tho and click the button, it does not do this, everyones perms remain as true.

gilded depot
vocal snow
#
        for team1_member in team1:
            await channel.set_permissions(team1_member, read_messages=True, send_messages=True)
        for team2_member in team2:
            await channel.set_permissions(team2_member, read_messages=True, send_messages=True)
``` why are you enabling the permissions if you're going to disable them anyways
gilded depot
#

thats for when the v=channel is first created

#

after which the discord bot sends a button

#

when its clicked, that wehn I want it to disable perms

naive briar
#

That's a lot of unnecessary requests

#

The setting permissions part, I mean

gilded depot
#

I see

#

so how should iu change this so it is less "unnecessary"

#

?

naive briar
#

I was thinking

#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.11)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
naive briar
#

The overwrites argument, you can set permission overwrites immediately after creating the channel

gilded depot
#

ok

gilded depot
#

and this should help?

naive briar
#

About making unnecessary requests, yes

gilded depot
#

?

#

but thanks @naive briar updating my code now, should this disable the user's perms when I click the button?

#

wait

#

bruh

#

I wrote overwrite instead of overwrites:

await channel.set_permissions(member, overwrite=discord.PermissionOverwrite(send_messages=False))
#

oops

#

maybe not

gloomy hound
#

Hi, I was wondering, would you use inherited class for cogs :

from discord.ext import commands

class MyCog(commands.Cog):
  def __init__(self):
    super().__init__()

  @commands.slash_command()
  async def foo(self):
    print("foo")

or just a cog instance ?

from discord.ext import commands

myCog = commands.Cog()

@myCog.slash_command()
async def foo():
  print("foo")

There are maybe mistakes in the second version cuz I never used it

slate swan
#

A cog subclass

gloomy hound
#

why ?

naive briar
unkempt canyonBOT
#
I'm sorry Dave, I'm afraid I can't do that.

No documentation found for the requested symbol.

naive briar
gloomy hound
#

I asked ChatGPT he said same as u but cuz it was better to access bot class

naive briar
#

And the second one isn't even valid

gloomy hound
gloomy hound
naive briar
#

The first also isn't valid ducky_skull

gloomy hound
#

oh ye forgot self

naive briar
#

Why would there be a slash_command decorator in the discord.ext.commands module

gloomy hound
#

idk tbh I don't really understand decorators

#

and there is one

#

cuz I use this syntax for my bot

naive briar
gloomy hound
naive briar
#

Where is it then

gloomy hound
#

for slash_command in discord.ext.commands

#
@commands.slash_command(name="ask", description="Ask anything to ChatGPT!")
#

Actually working code ^

naive briar
#

I doubt if commands is discord.ext.commands

gloomy hound
#

discord.ext.commands

#
from discord.ext import commands
naive briar
#

If whatever library you are using actually has it, then it got a weird implementation

gloomy hound
#

from the same script^

gloomy hound
#

what should I use

#

then saw it was deprecated

naive briar
#

The discord.ext.commands is originally made for developers to make prefix commands easily

gloomy hound
#

So I saw pycord

naive briar
gloomy hound
#

but it's still. Isn't it ?

naive briar
#

No

unkempt canyonBOT
gloomy hound
#

it's not deprecated anymore ?!?

#

dang

slate swan
#

Pycord isn't mantained anymore?

gloomy hound
#

wait why are there like 100+ packages for discord ??

naive briar
#

Its last update is a week ago

gloomy hound
#

;-;

slate swan
gloomy hound
#

and which one is better ? :p

slate swan
gloomy hound
#

so not really useful right ?

slate swan
gloomy hound
slate swan
#

But discord.py is more used hence more examples online

gloomy hound
#

decorators are likely one of the only things I don't get at all

slate swan
slate swan
#

If you come from pycord i suggest nextcord

gloomy hound
#

ok

#

thanks

slate swan
#

!e

def do_twice(func):
    def predicate():
        func()
        func()
    return predicate

@do_twice
def do_thing():
    print('Hello!')

do_thing()
unkempt canyonBOT
#

@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | Hello!
002 | Hello!
slate swan
#

In the case of something like @bot.command it's just taking your function, converting it into a Command object and registering it with your bot

gloomy hound
#

Oh so it's like a callback called somewhere into the function ?

#

@slate swan

plucky sun
#

How to fix?

  File "C:\Users\KokoG\PycharmProjects\Discord Bots\D-SERV PAYMENTS\payments.py", line 90, in <module>
    class PayPal(discord.ui.View):
  File "C:\Users\KokoG\PycharmProjects\Discord Bots\D-SERV PAYMENTS\payments.py", line 99, in PayPal
    @discord.ui.button(label='Link',style=discord.ButtonStyle.link, url='https://www.paypal.me/dservgaming', emoji='')
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: button() got an unexpected keyword argument 'url'```
#

@slate swan

upbeat ice
#

read the error

plucky sun
#

What should I replace it with ?

upbeat ice
#

Buttons with a URL cannot be created with this function. Consider creating a Button manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.

#

In other words, create the button manually and not in the decorator

velvet sierra
#

guys, i have a command like

@bot.hybrid_command(name="test", with_app_command=True, description="test")
async def test(ctx):
  x = 5
  while x < 10:
    if x > 10:
      print('thats just a example')
      break

my question is: when the user type the /test command twice can i break the while of a previous command? i know how to break it with a timeout, but i want know if it is possible for when the user type the command again it instantly break the while of previous command

harsh orbit
upbeat ice
light jungle
#

How do I delete the last 2 messages?

tall temple
#

hey please how can i create a channel in a specific place in a category with create_text_channel() method or else ?

upbeat ice
unkempt canyonBOT
#

await delete_messages(messages, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Deletes a list of messages. This is similar to [`Message.delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.delete "discord.Message.delete") except it bulk deletes multiple messages.

As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.

You cannot bulk delete more than 100 messages or messages that are older than 14 days old.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this...
harsh orbit
tall temple
upbeat ice
unkempt canyonBOT
#

await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
tall temple
slate swan
#

bro can someone help me im about to ropemax

#

i coded this command for so long and its been working randomly i add some code to add a button to the embed

#

and then my command disappears

#

then i reload the cog

#

and resync it, then it comes back

#

but now the option is gone

#

like the command was /whois user:

#

now user disappeared

#

so its just /whois

#

BRO IM LITERALLY GONNA *FF myself anyone know the problem

#

i hate slash commands

#

im not about to scrap EVERYTHING ive just worked on bruh

#

ichanged my bot token i tried a different server i tried a different account with a different bot token nothing works

#

i deleted the cog and put the code in a different cog, idont think the problem is the code or my ide i think its discord but IDK HOW TO FIX IT

#

Posting the code itself tends to help us help you

slate swan
#

my code isnt the problem

#

actually yeah one sec

#

opps

#

lemme grab code block

#
@commands.cooldown(1, 3, commands.BucketType.user)
    async def user(self, interaction: discord.Interaction):
        # Get the entered username from the user
        username = interaction.data["options"][0]["value"]```
#

this is practically the only relevant thing

slate swan
#

dang im stranded

#

with no help great

#

!d options

#

im ropemaxxing

slate swan
slate swan
#

Or whatever it’s called

#

It’s been working for a while

#

I've never used that nor really know what it is so I probably can't help

vale wing
#

It's for people who can't code exec command by themselves

slate swan
#

Jishaku is Like you can insert code to your bot on runtime

#

!pypi jishaku

unkempt canyonBOT
slate swan
#

plus I recoded most of it by myself

hushed galleon
#

have you been manually registering the command options with discord's API this whole time?

#

that use of interaction.data is very hacky too

plush pond
#

how do I add users to a guild using the guild join scope?

#

I tried following the docs but it was too hard to understand and it didn't work for me

slate swan
#

The guild join scope is not applicable in discord bot

#

Its for discord apps and you need redirect URL for that

#

And a running server that handles the requests

slate swan
#

thats how it looked like with the code

#

it just popped up

#

and it got the information and everything

#

and it was working perfectly fine

hushed galleon
#

seems like you had it correct at one point but you removed the user parameter and only recently synced the command, which made it disappear

slate swan
#
from discord import app_commands
from discord.ext import commands
from discord.ui import View, Select
import requests```
#

these are my libs

slate swan
hushed galleon
#

add your user parameter back and use that in your command instead of interaction.data, e.g. py @app_commands.command() async def my_command(self, interaction, user: discord.Member): ... # ^^^^^^^^^^^^^^^^^^^^ also sync your command afterwards

slate swan
#

and when i tried them nothing camp up

slate swan
#

its a user

#

like for another platform

#

for roblox

hushed galleon
#

oh yeah

slate swan
#

so my code grabs that does alot of api stuff and puts info out

hushed galleon
#

typehint it whatever you want it to be

slate swan
#

the user can type in what they want

#

and then i recieve it

#

with interaction.data take it find the user grab the id them use the id for other apis to grab info about the user then display it

hushed galleon
#

i meant type hint it as whatever type that you want the user to write in, a string, integer, whatever

slate swan
slate swan
#

like what I can edit, and im still confused how it just disappeared

#

yes but discord.member

#

means mentioning a member if im correct

#

but the user just needs to type the name out

hushed galleon
slate swan
#

but im still confused, how would i make it so the user can type just letters

#

and numbers in the box

#

like how it was before i dont think im understanding

#

because i checked the first version of my code and i used the same method for this specific cog

#

and its being loaded properly and everything and synced

#

so im confused

hushed galleon
#

you typehint it as a string type, str

slate swan
#

ok

#

checking if it works

#

idk how it was working before tbh

slate swan
#

it worked and my code works again idk even know how it worked before

#

and now i dont need to use the work around

#

to grab the info

hushed galleon
#

discord has its own version of the command structure that you first synced, meaning you can change or get rid of it and the slash command will still exist until you sync again

slate swan
#

and editing the code and its been working. until i added something then my orginal method just completely crashed

#

although its fixed now so thank you so much

#

i almost had to scrap the code

tall temple
#

hey please is there a selector for guild roles in a slash command like discord.Option(discord.Member) ?

slate swan
#

yes you just annotate it as discord.Role

tall temple
tall temple
#

Please what this error means ?

#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 599, in register_commands
    registered = await register("bulk", data, _log=False)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 371, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 7: Application command names must be unique
slate swan
shrewd parrot
#
discord.ext.commands.errors.ExtensionFailed: Extension 'lib.commands.general' raised an error: TypeError: object NoneType can't be used in 'await' expression

I get this error when trying to load extensions for discord.py, I've attached my file tree- any ideas on what I did wrong?

slate swan
#

looks like general.py is throwing an error when being loaded, you'll have to show the code you have inside the file

stone gate
#

hey i was wondering, i know that some bots display the user list when trying to a autocomplete an object (in interactions)

like this

#

how can i do the same thing?

upbeat mason
#

No clue why I keep getting this error in my code:

2023-08-01 02:39:33 ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "warn" is not found

The command itself:

@client.command()
async def vwarn(ctx, user: discord.Member, *, reason: str):
    await log_command(ctx, "warn", f"{user.mention} - {reason}")
    embed = discord.Embed(title="You've been warned!", color=discord.Color.orange())
    embed.add_field(name="Moderator", value=ctx.author.mention, inline=False)
    embed.add_field(name="Reason", value=reason, inline=False)
    await user.send(embed=embed)
slate swan
slate swan
upbeat mason
#
import discord
import asyncio
from discord.ext import commands, tasks
from discord.utils import utcnow

client = commands.Bot(command_prefix="v", intents=discord.Intents.all())

guild_id = 1135722213287395338
community_member = 1135725714675601489
moderator = 1135725652054646824
senior = 1135725549961097367
logs = 1135723280997822605

moderator_role = None
senior_role = None
mod_logs_channel = None

@client.event
async def on_ready():
    global moderator_role, senior_role, mod_logs_channel
    print("\x1b[38;5;41m[SUCCESS] Bot Online")

    guild = client.get_guild(guild_id)
    moderator_role = discord.utils.get(guild.roles, id=moderator)
    senior_role = discord.utils.get(guild.roles, id=senior)
    mod_logs_channel = client.get_channel(logs)

    await update_activity_loop()

async def update_activity_loop():
    while True:
        await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="Victoria County Staff"))
        await asyncio.sleep(10)
        total_users = sum(len(guild.members) for guild in client.guilds)
        await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"{total_users} users!"))
        await asyncio.sleep(10)

async def log_command(ctx, action, arguments):
    embed = discord.Embed(title="Command Log", color=discord.Color.orange())
    embed.add_field(name="Moderator", value=ctx.author.mention, inline=False)
    embed.add_field(name="Action", value=action, inline=False)
    embed.add_field(name="Arguments", value=arguments if arguments else "N/A", inline=False)
    await mod_logs_channel.send(embed=embed)

@client.command()
async def ping(ctx):
    timestamp = utcnow()
    embed = discord.Embed(title="Pong!", color=discord.Color.orange())
    message = await ctx.send(embed=embed)
    latency = (utcnow() - timestamp).total_seconds() * 1000
    embed.add_field(name="Latency", value=f"{latency}ms", inline=False)
    await message.edit(embed=embed)

    await log_command(ctx, "ping", None)

@client.command()
async def vmodlogs(ctx, user: discord.User):
    await ctx.send(f"Modlogs for {user.mention}")

@client.command()
async def vwarn(ctx, user: discord.Member, *, reason: str):
    await log_command(ctx, "warn", f"{user.mention} - {reason}")
    embed = discord.Embed(title="You've been warned!", color=discord.Color.orange())
    embed.add_field(name="Moderator", value=ctx.author.mention, inline=False)
    embed.add_field(name="Reason", value=reason, inline=False)
    await user.send(embed=embed)

client.remove_command('help')

client.run("token")

@slate swan full code i guess

slate swan
stone gate
#

i dont know what to add though- Im a really slow learner

upbeat mason
slate swan
upbeat mason
#

nope

#

the ping command works fine

slate swan
#

well i dont see warn command here either

#

i only see vwarn

upbeat mason
#

yeah the prefix is "v" and earlier putting the v there somehow fixed it

slate swan
upbeat mason
#

let me try it without

slate swan
#

now interaction is of type discord.Interaction

#

!d discord.Interaction

unkempt canyonBOT
#

class discord.Interaction```
Represents a Discord interaction.

An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.

New in version 2.0.
upbeat mason
#

alright thanks for your help,

#

got it to work

stone gate
#

so interaction: discord.Interaction

slate swan
#

try and see

stone gate
#

TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>

slate swan
#

is this command within a class?

turbid condor
#

What's interactions.Interaction?

stone gate
#

if you mean a cog? yes.

slate swan
slate swan
stone gate
#

what do you want to see exactly?

turbid condor
#

The cog

unkempt canyonBOT
#

discord/interactions.py line 93

class Interaction(Generic[ClientT]):```
slate swan
#

its just inside interactions file hence python shows it as this

turbid condor
#

I see

stone gate
slate swan
#
class X:
    ...
    # this is inside class

...
# this is not
stone gate
#

oh-

#

i am so stupid oh god

turbid condor
#

And doesn't interaction come before button arg in buttons?

slate swan
turbid condor
#

Then why he/she using it the other way

slate swan
turbid condor
#

Cuz i think they are using dpy from discord.app_commands

slate swan
stone gate
#

tried to follow documentation, but turns out having adhd and english not being my first language is something that helps in that regard-

slate swan
#

!d discord.ui.button @stone gate example can be found here

unkempt canyonBOT
#

@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.

Note

Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
slate swan
#

or maybe no

#

apparently button does not have an example

turbid condor
#

They do

#

Here this

unkempt canyonBOT
#

examples/views/confirm.py lines 29 to 30

@discord.ui.button(label='Confirm', style=discord.ButtonStyle.green)
async def confirm(self, interaction: discord.Interaction, button: discord.ui.Button):```
slate swan
#

!d discord.ui.select this does

unkempt canyonBOT
#

@discord.ui.select(*, cls=discord.ui.select.Select[+ V], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, row=None)```
A decorator that attaches a select menu to a component.

The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the chosen select class.

To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
turbid condor
#

Welp docs of dpy have few examples in there docs

stone gate
#

no wait

#

arent i doing exactly what the example says?

slate swan
#

no you have arguments swapped

stone gate
#

could you elaborate? sorry

turbid condor
stone gate
#

OHHH i see

#

it seems to work now! thanks!

stone gate
#

https://paste.pythondiscord.com/CZSA back again, i dont know what happened but now commands arent recognised at all. It seems to be the Button class, if i remove it, the commands are read just fine?

frosty beacon
#

!d discord.ext.commands.command

unkempt canyonBOT
#

@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").

By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") using utf-8 encoding.

All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
sick birch
stone gate
sick birch
finite geyser
stone gate
#

https://paste.pythondiscord.com/3XUQ dont mind my weird jump between spanish and english, and some inconsistencies, its either my brain turning off or help from a friend, or some times a little bit of AI help

#

also its rough because i had to move a good chunk of the database from a trashy sql service that crashed every 5 requests to google sheets

slate swan
#

Im having trouble listing commands using cogs and app_commands. Ive tried get_app_commands with examples online but no success yet

naive briar
#

What's the problem

sick birch
sick birch
slate swan
# naive briar What's the problem

i dont know how to implement that into the code, was imagining something similar

@app_commands.command(name="help", description="help msg")
    async def help(self, interaction: discord.Interaction):
        
        commands = (self.get_app_commands())
         for command in commands
            print(command)
- TypeError: 'trainer' object is not iterable
stone gate
sick birch
stone gate
sick birch
#

By moving the app commands into the cog rather than the view

#

Might be easier to move the view somewhere else instead

unkempt canyonBOT
#
Traceback

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

stone gate
sick birch
#

Top of file or bottom of file

#

Probably top actually if you want to reference it

slate swan
#
- ERROR    discord.app_commands.tree Ignoring exception in command 'help'
Traceback (most recent call last):
  File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
  File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\cogs\shop\trainer.py", line 1397, in help
    for command in self:
TypeError: 'trainer' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "c:\Users\devon\Documents\1-CODING\activateBots\narutoBot2.0\env\lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'help' raised an exception: TypeError: 'trainer' object is not iterable
stone gate
naive briar
#

And wait a minute, at line 1397!?

sick birch
#

Basically what your issue is you have a class (cog) and it's broken up by the view in the middle

#

So everything after the view is considered to be part of the view because of python indents

stone gate
#

oh, i see

sick birch
#

Methods are methods of classes that are closest above it, so if you trace your tag command, you will see the closest class above it is the view

stone gate
#

so i put the view above the cog?

#

so that commands are inside the cog

sick birch
#

yes

slate swan
#

and if I try to print it out right i get [<discord.app_commands.commands.Command object at 0x0000019C80B1CDF0>, <discord.app_commands.commands.Command object at 0x0000019C80B1CE20>, <discord.app_commands.commands.Command object at 0x0000019C80B1CE50>]

naive briar
slate swan
naive briar
#

Don't do it?

sick birch
#

It looks like you want to print all the app commands?

slate swan
#

or at least that cog

sick birch
#

You would loop over self.get_app_commands() then

clever scaffold
#

i think it working:

for commands in self.bot.commands:
  print(commands)
sick birch
#

That's not going to work

#

Well

slate swan
#

its app commands

naive briar
#

The code they sent was already correct, how come it turns into for command in self

sick birch
#

Technically it will but not sure it does what OP wants

naive briar
slate swan
#

i felt like it was correct but im getting an error that says its not iterable

naive briar
#

I don't know about you, but a list is sure iterable

#

The thing that is not iterable is your cog, that you're trying to iter for some reason

sick birch
slate swan
#

Thats exactly what i got

slate swan
sick birch
slate swan
# sick birch Can you paste the exact traceback too?
commands = self.get_app_commands()
    for command in commands:
       print(command)

right now what im getting is

<discord.app_commands.commands.Command object at 0x0000020D4FD1CEB0>

<discord.app_commands.commands.Command object at 0x0000020D4FD1CEE0>

<discord.app_commands.commands.Command object at 0x0000020D4FD1CF10>
#

Seems fine to me ☕

slate swan
naive briar
#

What

slate swan
# naive briar What
commands = self.get_app_commands()
    for command in commands:
      print(command.qualified_name)

it converts the <discord.app_commands.commands.Command object at 0x000001AA6801CE20> to the name of the command

wispy pasture
#

i want to edit the perms of a user or a role so that they can not use slash commands.... how do i do that?
right now i am stopping them from sending a message in the channel:
https://srcb.in/eyd4JQSGiY

but is there a way to jus stop themfrom using the slash cmds only?

slate swan
unkempt canyonBOT
frosty beacon
#
bot = TestBot(command_prefix="$", intents=intents)
logger = logging.FileHandler(filename="logs/discord.log", encoding="utf-8", mode="w+")
bot.run(KEY, log_handler=logger)

I have done basic logging setup.

_log = logging.getLogger(__name__)

is this the correct way to access logger in cogs??

hushed galleon
abstract kindle
#

would anyone know why when I do cntrl^c on my bot it takes forever to actually end the program

glad cradle
abstract kindle
glad cradle
glad cradle
#

in that case you wouldn't need to restart the Bot

abstract kindle
#

but the code im editing is not in a cog

glad cradle
#

is it in an extension?

abstract kindle
#

no

glad cradle
#

if it's in main.py then you always need to restart

abstract kindle
#

wait, are you saying that all code other than main.py should be in an extension?

glad cradle
#

no

brazen raft
#

Have you tried using the close method? Also, you could use importlib to programmatically re-import modules where needed

glad cradle
#

you can use importlib.reload to reload a module, but that's tricky to do

rare snow
#

hey

#

who pls can help

naive briar
#

Just ask your question

unborn shale
#

hey can anyone help me with my error

#

btw i am new to python to please dont judgee me😅

finite geyser
#

Error is Preety descriptive

finite geyser
finite geyser
#

Lol

gloomy hound
#

I was wondering if I do something like this :

import discord

class Bot(discord.ext.commands.Bot):
  def __init__(self):
    super().__init__()

  async def on_member_join(self, member: discord.Member):
    print(member.name, "joined")

How can I add the event decorator within the class ?

#

cuz currently the on_member_join will not be called

naive briar
#

It will

gloomy hound
#

oh

naive briar
#

The .event decorator just set the attribute to your callback function

gloomy hound
#

then

#

why doesn't it work when I try ?

naive briar
#

What happened then

gloomy hound
#

nothing...

naive briar
#

Show your full code

gloomy hound
#
from discord.ext import commands
import discord
import cogs

class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.members = True

        super().__init__(command_prefix="/", intents=intents)

        self.add_cog(cog=cogs.Greetings(self))
        self.add_cog(cog=cogs.Bot(self))
        self.add_cog(cog=cogs.ApiRequests(self))
        self.add_cog(cog=cogs.LocalGames(self))

    async def on_ready(self):
        print(f"Successfully logged in as {self.user.name}")

    async def on_disconnect(self):
        print(f"Disconnected from {self.user.name}")
#

the thing is in the greetings

#
import discord
from discord.ext import commands
import embeds

WELCOME_CHANNEL_ID = 1127663724635889818

class Greetings(commands.Cog):
    def __init__(self, bot: commands.Bot):
        super().__init__()
        self.bot = bot
 
    async def on_member_join(self, member: discord.Member):
        welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
        welcome_channel.send(embed=embeds.Welcome(member))

    async def on_member_remove(self, member: discord.Member):
        welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
        welcome_channel.send(embed=embeds.Goodbye(member))
naive briar
#

You need to declare them as listeners by using discord.ext.commands.Cog.listen

gloomy hound
#

how

naive briar
#

It's not the same thing as events

naive briar
unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
naive briar
#

It's a decorator

gloomy hound
# naive briar It's a decorator

like this ?

import discord
from discord.ext import commands
import embeds

WELCOME_CHANNEL_ID = 1127663724635889818

class Greetings(commands.Cog):
    def __init__(self, bot: commands.Bot):
        super().__init__()
        self.bot = bot

    @commands.Cog.listen("on_member_join")
    async def on_member_join(self, member: discord.Member):
        welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
        welcome_channel.send(embed=embeds.Welcome(member))

    @commands.Cog.listen("on_member_remove")
    async def on_member_remove(self, member: discord.Member):
        welcome_channel = self.bot.get_channel(WELCOME_CHANNEL_ID)
        welcome_channel.send(embed=embeds.Goodbye(member))
naive briar
#

Mistyped it, listener not listen

gloomy hound
#

oo

#

how is it different ?

naive briar
#

listen doesn't exist

gloomy hound
#

ok

gloomy hound
naive briar
#

No

gloomy hound
#

ok

#

sad

slate swan
#

Me when people are too lazy to create a secondary account to test anything they want

rare snow
#

i m trying to make the bot play a music using ffmpeg it works fine when i going to play another song he doesn't and thats because theres error in the package i don't what this what vs code show me :

Traceback (most recent call last):
  File "C:\Users\Nassim\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Nassim\Desktop\dogs\main.py", line 34, in on_message
    voice_p = await voice_channel.disconnect()
                    ^^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'voice_channel' where it is not associated with a value
#

await voice_channel

naive briar
#

Show your code

#

!e

def a():
    if True:
        b + 1
    else:
        b = 0

a()
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 7, in <module>
003 |     a()
004 |   File "/home/main.py", line 3, in a
005 |     b + 1
006 |     ^
007 | UnboundLocalError: cannot access local variable 'b' where it is not associated with a value
gloomy hound
#

stupid question : Are alt allowed on discord or I have to use a name that is not recognizable ?

naive briar
#

Why wouldn't it be?

gloomy hound
naive briar
#

Unless you'd use it for to bypass bans

gloomy hound
#

ok ty

naive briar
gloomy hound
#

ye true

ember mango
#

Can I create an economy؟ with Python.?

buoyant quail
#

No one will stop you from doing it

fading linden
#

so im having an issue with using sqlite on a bot hosting service

its a case of "it runs locally but broken online"

it spews this error on the host's console:
DatabaseError: malformed database schema (tmdb) - near "STRICT": syntax error
locally, the query runs just fine, im on the same python version both on the host and locally (3.11.2)

night crater
#

is it using different sqlite versions?

honest falcon
#

Anyway to install playwright on android? I have a discord bot that need playwright to run (yes im hosting a bot on android, it free and it work, so why not)
Whenever i tried to install it with pip on pydroid it said cant find any version that satisfied the requirements

vale wing
fading linden
#

seems like the service doesn't support strict mode

#

which is weird

fading linden
#

i rebuilt the database without strict mode and voila it worked

finite geyser
wispy pasture
#

sooo.... this is my code:

        pollination_embed = discord.Embed(description="# Artwork Information:", color=0x714fff)
        if isinstance(ctx.author, discord.Member) and hasattr(ctx.author, 'avatar_url'):
    # If ctx.author is a Member object and has an avatar, use it as the author's icon
            pollination_embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
        else:
    # If ctx.author is not a Member object or doesn't have an avatar, set a default icon or omit the icon_url
            pollination_embed.set_author(name=ctx.author.display_name)       

        pollination_embed.add_field(name="Prompt used for Image Generation:", value=f">>> {prompt}", inline=False)
        pollination_embed.add_field(name="Visual Setting", value=f">>> {ratio.name}", inline=False)
        pollination_embed.set_footer(text=f'Creativity is inventing, experimenting, growing, taking risks, breaking rules, making mistakes, and having fun.')```

i want it to show my pfp as well.... how can i do that
slate swan
#

Well it's avatar.url and not avatar_url

#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
wispy pasture
upbeat mason
#
@client.slash_command(description="Bot Information")
async def information(ctx):
    embed = discord.Embed(title="Bot Information", color=discord.Color.orange())
    embed.add_field(name="Bot Creator", value="duhphil", inline=False)
    embed.add_field(name="Server", value="Victoria County", inline=False)
    await ctx.send(embed=embed)

i'm getting an error:

Traceback (most recent call last):
  File "c:\Users\phil\Desktop\projects\python\VMod\main.py", line 172, in <module>
    @client.slash_command(description="Bot Information")
     ^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?

i have no clue what the issue is

slate swan
#

whats the tree event ? for ctx one its @bot.event but what is the tree event? its not @tree.event btw

slate swan