#discord-bots

1 messages · Page 151 of 1

sick birch
fading marlin
#

!d discord.ext.commands.Context.guild this returns the guild in which the command was executed

unkempt canyonBOT
naive briar
#

Explanation ducky_angel

thorn python
#

What is the difference between instance and class?

#

Sorry, I am learning and coding together

winged coral
#

The class is the "template" for an instance

#

An instance is when a class is called and then an instance of the class is created

#

Typically it has an init method which runs when an instance is created but it doesn't necessarily need one

#
class Foo:
    ...

bar = Foo()
#

Foo is a class, bar stores an instance of the class Foo

thorn python
#
    for name in lista:
        instance = Guild.create_role(name=name)
        await instance```
#

I changed to this

#

Still getting the same error

thorn python
#

I read this

#

And I found nothing helpful

sick birch
fading marlin
#

ctx is an instance of commands.Context, therefore it has an attribute called guild (as shown in the docs) which returns what you need

sick birch
#

You want an actual instance to perform actions on

#

Analogous to using a recipe to actually make an edible dish, then adding salt to that

glad cradle
thorn python
#

I guess it's no use to try to code a bot right now...

#

Maybe I should exercice some OOP

fading marlin
#

discord bots aren't the most beginner friendly projects to work on 🤷

thorn python
#

I tried to advence before

winged coral
#

Projects that challenge your existing knowledge are pretty good as long as you have that knowledge to an extent

thorn python
#

That's what I need

winged coral
#

Then OOP is a great start

thorn python
#

Ok

#

Thanks!

brisk hull
#

hello, ive been cleared by the mods to request and receive help in making my recording bot, ive made a bit of progress but im stuck on some stuff.

this once_done line is a bit confusing i would appreciate help understanding it

  vc.start_recording(
        discord.sinks.WaveSink(), # the sink type to use
        once_done, #what to do when done
        ctx.channel #the channel to disconnect from
    )```
brisk hull
abstract kindle
#

I know this isn't python, but does anyone know if D++ is a good C++ wrapper?

brisk hull
#

ive never attempted a project like this so im a bit/ extremely green about understanding whats goin on

sick birch
brisk hull
#

darn

#

so far it joins vc with me

rancid grail
#

Just for the record, we did clear them 👍

brisk hull
#

yeah to be extra transparent im building a tool to record podcasts in VC and im aiming for multi speaker recordings, ive seen my boss do this in pycord but im supposed to find out without asking him so im trying to get some help on it. the bot has extremely clear alerts that it is recording, and i will be adding in a ping to users in the VC to make them EXTRA aware. there are 0 ethical concerns and in the future id like to be able to create a speaker role so only those with the role can be recorded in general to allow the rest of the users to speak freely during recordings

#

i want it to be able to hop into a VC with like 4 ppl and record 4 sets of audio so that the user can receive the audio and master it on their own.

timid spade
#

i want to add my SelectOptions in an __init__ function while sub classing discord.ui.select using discord.py
but i have used select.append_option to add options
how can i add them in __init__ funtion?

sick birch
pliant gulch
#

Maybe some libraries have it documented. Like in Java cord or whatever it was

#

I know d++ also has it iirc?

errant pecan
#
    @commands.slash_command(name = 'say', description="Сказать от имени бота. \n Пример: /say сообщение")
    @commands.has_permissions(administrator = True)
    async def ___say__(self, interaction: discord.Interaction, *, message):
        if commands.MissingPermissions():
            embed = discord.Embed(description = 'ERROR', colour=0x2F3136)
            await interaction.response.send_message(embed=embed)
            return
        embed = discord.Embed(colour=0x87CEEB)
        embed.add_field(name='**Объявление**', value= message, inline=False)
        await interaction.response.send_message(embed=embed)```
how can I make it so that if a participant does not have administrator rights , an error is given to him when writing a message ??
#

all logical more logical ways don't work. although what is the logic in Python. He's worse than a girl who has her period...

timid spade
errant pecan
#

thanks. I realized that this is a useless function

timid spade
#

nice

errant pecan
errant pecan
# timid spade nice

do you need a new class for each new team , or is it possible to do everything in one ?

timid spade
#

for example

#
async def purge_error(ctx, error):
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You cant do that!")```
brisk hull
timid spade
errant pecan
timid spade
errant pecan
#
    @commands.slash_command(name = 'say', description="Сказать от имени бота. \n Пример: /say сообщение")
    @commands.has_permissions(administrator = True)
    async def say(self, interaction: discord.Interaction, *, message):
        embed = discord.Embed(colour=0x87CEEB)
        embed.add_field(name='**Объявление**', value= message, inline=False)
        await interaction.response.send_message(embed=embed)
    @say.error
    async def on_say_error(self, error, interaction: discord.Interaction):
        if isinstance(error, discord.ext.commands.errors.MissingPermissions):
            await interaction.response.send_message("<message you want to send>")```
it didn't work. And there is no error in the console either
#

@timid spade

slate swan
#
@bot.command()
async def partner(ctx, guild):
   if ctx.author.guild_permissions.manage_messages:
      async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
          await cursor.execute("SELECT ad, adchannel FROM users WHERE guild = ?", (ctx.guild.id,))
          guild1 = await cursor.fetchone()
          await cursor.execute("SELECT ad, adchannel FROM users WHERE guild = ?", (guild,))
          guild2 = await cursor.fetchone()
          if guild is None:
            await ctx.send("You dont have an ad/adchannel setup.")
          else:
            if guild2 is None:
              await ctx.send("The guild your trying to partner with doesnt have an ad/adchannel setup.")
            else:
              channel = guild1[1]
              ad = guild1[0]
              channel2 = guild2[1]
              ad2 = guild2[0]
              await channel.send(ad2)
              await channel2.send(ad)
#

why does this send no message/

timid spade
frosty umbra
#

Discord bots can use animated emojis no matter what right?

#

As long as its an emoji from the server

slate swan
#

use from any server

#
        await cursor.execute('UPDATE users SET id = ? WHERE ad = ? AND guild = ?, AND welcomechannel = ?, AND announcechannel = ?, AND welcomemessage = ?, AND leavemessage = ?, AND adchannel = ?', (member.id, '', ctx.guild.id, 0, 0, '', '', 0,))
#
Traceback (most recent call last):
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "main.py", line 140, in setup
    await cursor.execute('UPDATE users SET id = ? WHERE ad = ? AND guild = ?, AND welcomechannel = ?, AND announcechannel = ?, AND welcomemessage = ?, AND leavemessage = ?, AND adchannel = ?', (member.id, '', ctx.guild.id, 0, 0, '', '', 0,))
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 129, in _execute
    return await future
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/aiosqlite/core.py", line 102, in run
    result = function()
sqlite3.OperationalError: near ",": syntax error

The above exception was the direct cause of the following exception:
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "/home/runner/cross-ad-bot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: near ",": syntax error
timid spade
dusk pumice
#

eyyyyyy
What lib U guys usin' these days

#

Is dpy still alive?

rare echo
#

yes

#

personal preference at this point, some libs may have more prebuilt

slate swan
slate swan
bright wedge
#
await msg.edit(embed=bans_kicks_msg[0].set_field_at(index=0,name="Test",value="0"))
TypeError: 'Message' object is not subscriptable
pliant gulch
#

Got a working POC 🥶 hella type errors because Event[...]

bright wedge
primal token
pliant gulch
#

Probably

#

It's only screaming because it's Unknown since no types have been passed

slate swan
#

just add #type: ignores

#

on the top of file

primal token
pliant gulch
#

how does POC look so far

primal token
#

POC?

pliant gulch
#

proof-of-concept

#

I need to add gateway polling, rest and ratelimits then it should be off to models

#

Maybe rin is possible in 2022 after all

slate swan
# pliant gulch

but shouldn't it automatically decide the type when you're initialising the Event class there itself

pliant gulch
#

It's unknown

primal token
pliant gulch
#

You need to do ```py
MESSAGE_CREATE = Eventstr

#

str or any other

slate swan
#

ohh makes sense

primal token
pliant gulch
#

It exists because callback signature (str) -> Coroutine[Any, Any, Any]

#

So if it is instead (int) -> ... it'll type error

slate swan
#

with on_message_delete

#

how can I test the sender of the message

sick birch
#

what wm and editor is that

short pulsar
#

how do i

#

make a bot that that gets information on a roblox playert

#
import discord
from discord.ext import commands
from discord import app_commands
import requests

response = requests.get("https://api.roblox.com/users/905112394")



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


@client.command()
async def info(ctx, response):
    await ctx.send(response.text)
    


client.run(no)
#

heres my code

pliant gulch
#

Also Yabai WM & Neovim

#

My terminal has transparency so that's just my wallpaper not a theme specific bg on neovim

sick birch
#

ah nice. i'm getting tired of KDE lol

#

I like your neovim, though

pliant gulch
#

I want to redo it since my file tree config sucks ass

#

I wanna switch over to flat colours and what not

crude hawk
#

I need help with my code

  role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
  username = client.get_user(user_id)
  user = discord. utils. get(ctx.guild.members, )
  if role in username.roles:
    print("Role detected")
  else:
    print("No Role Found")```
Im trying to make it detect if they have the Member role but I get this error:
`NameError: name 'client' is not defined`
Can anyone help?
slate swan
#
              if guild2 is None:
                await ctx.send("The guild your trying to partner with doesnt have an ad/adchannel setup.")
              if guild1 and guild2 is not None:
                ad, channel = guild1
                ad2, channel2 = guild2
                emb = discord.embed(title=f'Partnership From {guildid}', description=f'{ad2}')
                em = discord.embed(title=f'Partnership From {ctx.guild.id}', description=f'{ad}')
                channel = int(channel)
                channel2 = int(channel2)
                await channel.send(embed=emb)
                await channel2.send(embed=em)
#

this isnt sending any messages, anyone help?

slate swan
#
                guildname = guild
                guildname = bot.get_guild(guildname)
                print("partner1")
                ad, channel = guild1
                ad2, channel2 = guild2
                print("partner2")                
                emb = discord.Embed(title=f'Partnership From {guildname}', description=f'{ad2}')
                print("partner3")
                em = discord.Embed(title=f'Partnership From {ctx.guild}', description=f'{ad}')
                print("partner4")
                channel = bot.get_channel(channel)
                channel2 = bot.get_channel(channel2)
                await channel.send(embed=emb)
                await channel2.send(embed=em)
                print("partner5")
#

keeps saying None even tho im getting the guild

#

channel2=bot.get_channel(int(channel2)

#

The bot must be in that server to get the name and other information

#

it is

#

you made me realize I was calling a obj not a int

#

Yep

slate swan
#

For guild information

#

ik

#

Nice

#

but guild was already got

#

so guild8 = guild
guild = bot.get_guild(guild)
guildid = guild8
guildname = guild8
guildname = bot.get_guild(int(guildname))

#

🤷

#

Guild name?

#

I was trying to get guild on the bottom part

#

It should guildid tho

#

guildname = guild8

#

which is a id'

#

Can u show the full code?

#

y

#

it's kinda hard to understand 🌚

#

Like what is the var guild

#

async def partner(ctx, guild):

#

ctx, guild: int):

rare echo
#

for paginator how can i append pages in a loop to where its a separate page for each entry? or simply implement a counter per page?

#

because right now im getting a very long paginator embed but instead i want each entry on its own page

slate swan
#

Counter not always better as because it will always goes up while others are clicking too 🤷

#

But u can use counter too tho

rare echo
#

its one person cmd with ephemeral send

#

but my problem is i cant just simply embed[i] and use i as counter yk

slate swan
rare echo
#

yeah but how do i differentiate the embed?

slate swan
#

embed=[embed1,embed2,embed3]

rare echo
#

ok but

#

how am i adding the end x)

slate swan
#

then if user clicks a button i should be 0 tho

rare echo
#

yeah i got everything else in the noggin

#

i just need to figure out how to separate these embeds

slate swan
#

If i is 0 then it will send the first embed means embed 1

#

then second click
i will be 1
then
embed[i] will send 2nd embed means embed 2 from the list

#

In coding language counter starts from 0

rare echo
#
for x in y:
    Page(
        embeds=[embed.add_field(name='name', value=info)],
    )
 result.append(embed)```
slate swan
#

But from ourselves is 1

rare echo
#

for ex

#

omfg

slate swan
#

embeds*

rare echo
#

its because im adding fields to embeds not making them

slate swan
#

Xd

rare echo
#

ive been staring at this too long

slate swan
#

U have to make separate embeds xd

rare echo
#

yes ty lmao

slate swan
#

Ye xd

torn sail
#

When I use Bot.unload_extension , does it automatically remove all commands added in the setup function for Bot.load_extension?

fading marlin
#

Yes

unkempt canyonBOT
#

discord/ext/commands/bot.py line 885

async def _remove_module_references(self, name: str) -> None:```
torn sail
#

also do slash command default perms work on subcommands?

fading marlin
#

Yes, the subcommand's default permissions are set to whatever the parent's default permission is. You can't have a single subcommand with a different permission though iirc

torn sail
#

oh

slate swan
#

subcommands are just command options in the shadows lol

#

I use for spaces in slash command XD

timid spade
#

How can I put the .append options in discord.ui.select()?
I used loops to append options in selection menu now I have to put them in discord.ui.select()

slate swan
#

there's an options kwarg in the decorator, use it?

placid verge
#

How can i get the list of people who can send messages in a channel?

torn sail
placid verge
#
AttributeError: 'User' object has no attribute 'edit'
#

What wrong with this?

placid verge
#

It edits the user's nickname but after that it just gives an error in the console

naive briar
#

!d discord.Member.edit

unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
austere vale
#
/root/.pm2/logs/bot-error.log last 15 lines:
0|bot      | Ignoring exception in on_ready
0|bot      | Traceback (most recent call last):
0|bot      |   File "/usr/local/lib/python3.8/dist-packages/nextcord/client.py", line 502, in _run_event
0|bot      |     await coro(*args, **kwargs)
0|bot      |   File "/home/Runa/bot/main.py", line 22, in on_ready
0|bot      |     bot.db=await aiosqlite.connect('../db/level.db')
0|bot      |   File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 137, in _connect
0|bot      |     self._connection = await future
0|bot      |   File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 102, in run
0|bot      |     result = function()
0|bot      |   File "/usr/local/lib/python3.8/dist-packages/aiosqlite/core.py", line 397, in connector
0|bot      |     return sqlite3.connect(loc, **kwargs)
0|bot      | sqlite3.OperationalError: unable to open database file

can someone help me with my error please?

@bot.event
async def on_ready():
  bot.db=await aiosqlite.connect('../db/level.db')
  bot.db=await aiosqlite.connect('../db/bank.db')
  bot.db=await aiosqlite.connect('../db/blocked.db')
  db=sqlite3.connect('../db/main.sqlite')
rare echo
#

wut da hek

vocal snow
#

Why are you making multiple database files instead of just multiple tables?

#

And why use sqlite3 and aiosqlite togethe

austere vale
#

its my first time making a bot. could that be whats causing the error? it was working before

rare echo
austere vale
rare echo
#

just think about what can be combined

austere vale
#

ah okay

peak pewter
#
@client.tree.command(name='clear', description='deleteing messages')
async def purge(interaction: discord.Interaction, amount=int):
    if (not interaction.user.guild_permissions.manage_messages):
        embed=discord.Embed(title='Error :x: ', description=f'You don\'t have the permissions to run this command', color=0xe20909, timestamp = datetime.utcnow())
        embed.set_footer(text='Created by UniqueDolphin#8001')
        await interaction.response.send_message(embed=embed)
        return
    amount1 = amount+1
    if amount1 > 201:
        embed=discord.Embed(title='Error :x: ', description=f'I can\'t delete more than 200 messages at one time!', color=0xe20909, timestamp = datetime.utcnow())
        embed.set_footer(text='Created by UniqueDolphin#8001')
        await interaction.response.send_message(embed=embed)
    else:
        await interaction.channel.purge(limit=amount1)
        embed=discord.Embed(title='Succeeded :white_check_mark: ', description=f'i have deleted `{amount}` messages!', color=discord.Color.green(), timestamp = datetime.utcnow())
        embed.set_footer(text='Created by UniqueDolphin#8001')
        await interaction.response.send_message(embed=embed)
#

This is the error

flat pier
#

amount=int is not valid, you're saying this equals a type, rather then annotating it

flat pier
slate swan
#

please help me fixing this error

#

@flat pier

#

@austere vale

austere vale
#

please help me fix my error @slate swan

slate swan
rare echo
austere vale
rare echo
#

or it doesnt have permissions to access the file

#

maybe something opened it to modify and didnt close

#

¯_(ツ)_/¯

slate swan
flat pier
austere vale
#

ur making a mass dm bot-

rare echo
slate swan
austere vale
peak pewter
slate swan
#

how to fix it

peak pewter
#

this is how i do this

glad cradle
rare echo
slate swan
#

@flat pier its saying error here anywhere?

austere vale
rare echo
slate swan
flat pier
austere vale
rare echo
#

its taking too long so you need to defer it so it doesnt die while loading basically

glad cradle
# peak pewter I dont understand?

if the interaction takes more than 3 seconds to respond you need to "defer" the interaction, later you'll edit the original response (the defer response) with your message

rare echo
#

you are basically saying, yes im doing something its just taking a second

peak pewter
flat pier
#

You respond to the interaction with defer then you can followup later and send whatever message you need to send

glad cradle
flat pier
#

I just assume everyone is using dpy until they say they aren't

glad cradle
slate swan
#

anyone know if theres something specific I need to have "supports commands" on my bot? I use to have it on another one and its not showing up on my new one. My slash commands are registered and I have tried to make the bot public etc.

glad cradle
#

maybe you're slash commands aren't globally registered

flat pier
slate swan
#

thank you

whole sparrow
#

Guys, how long can I edit a message for before it doesnt work? Im editing a message once every 5 seconds but after 15 or so minutes it stops working

#

Is there a way to avoid this>

slate swan
whole sparrow
#

it's a slash command so not sure

#

just a slash command that get's edited every 5 seconds

#

slash command that creates an embed

#

then I use await inter.edit_original_message(embed=embed)

slate swan
#

you can't edit slash command responses after 15 minutes ( the interaction token expires)

#

just send a normal message instead

white citrus
#
class select_channels(nextcord.ui.View):
    def __init__(self, ctx_or_interaction, *, timeout=20):
        super().__init__(timeout=timeout)
        
        self.ctx_or_interaction = ctx_or_interaction
        if isinstance(ctx_or_interaction, Context):
            self.user = ctx_or_interaction.author
        if isinstance(ctx_or_interaction, Interaction):
            self.user = ctx_or_interaction.user
        
        
    async def interaction_check(self, interaction):
            
        if self.user == interaction.user:
            return True
        else:
            await interaction.response.send_message(content="You are not allow to select the channel!")
    
    
    @nextcord.ui.channel_select(channel_types=[nextcord.ChannelType.text], max_values=1, placeholder="Please choose one channel")  
    async def on_select(self, select: nextcord.ui.ChannelSelect, interaction: nextcord.Interaction):
        channels = select.values.channels
        for channel in channels:
            print(channel.id)
        
        data_default = {"_id": interaction.guild.id}  
        data = {"_id": interaction.guild.id, "global_id": channel.id}
        await interaction.client.settings.upsert(data_default, data)
        eb = self.children[0]
        eb.disabled = True
        eb.placeholder = f"You selected #{channel.name}"
        reply = nextcord.Embed(description=f"{config.DiscordTic} Thanks! You have activated your global chat. --> <#{channel.id}>", colour=config.green)
        await interaction.response.edit_message(embed=reply, view=self)
    
    async def on_timeout(self):
        eb = self.children[0]
        eb.disabled = True
        await self.message.edit(view=self)```
#
future: <Task finished name='discord-ui-view-timeout-e16c45d06ac9e9f60e732158c508ea01' coro=<select_channels.on_timeout() done, defined at c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py:195> exception=AttributeError("'select_channels' object has no attribute 'message'")>
Traceback (most recent call last):
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\views.py", line 198, in on_timeout
    await self.message.edit(view=self)
AttributeError: 'select_channels' object has no attribute 'message'```
naive briar
#

Where is message attribute defined?

white citrus
#

nowhere?

#

How else should I edit the message?

#

@naive briar

naive briar
#

Are you using slash command or prefix command

white citrus
naive briar
#

Since the send_message don't return anything, you have to set the message attribute for the view somehow, like with original_response, then edit it later.

view = ...

await interaction.response.send_message(...)
view.message = await interaction.original_response()

Or store the interaction that triggers the slash command and use edit_original_response.

view = ...
view.slash_interaction = interaction

await interaction.respose.send_message(...)
white citrus
#

Thank you @naive briar

white citrus
#
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 512, in _run_event
    await coro(*args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 191, in on_application_command_error
    raise error
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 910, in invoke_callback_with_hooks
    await self(interaction, *args, **kwargs)
  File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\setup\cog.py", line 549, in global_chat
    await inter.client.settings.unset(unset_date, unset_field)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\alaric\document.py", line 377, in unset
    await self._document.update_one(filter_dict, {"$unset": {field: True}})
TypeError: unhashable type: 'dict'```
#
            case "delete":
                dict_one = {"_id": inter.guild.id}
                exists_check = await inter.client.settings.find(dict_one)
                
                if exists_check is not None:
                    if "global_id" in exists_check:
                        c =  inter.client.get_channel(int(exists_check["global_id"]))
                        if c:
                            question = nextcord.Embed(description=f"{config.DiscordSupport} Are you sure to deactivate the global Chat ({c.mention})?")
                            
                            view = Yes_OR_No()

                            await inter.response.send_message(embed=question, ephemeral=True, view=view)
            
                            view.message = await inter.original_message()
            
                            await view.wait()
                            if view.value is None:
                                return
        
                            elif view.value:
                                unset_field = {"_id": inter.guild.id, "global_id": c.id}
                                unset_date = {"_id": inter.guild.id}
                                await inter.client.settings.unset(unset_date, unset_field)```
#

I use alaric

vale wing
white citrus
vale wing
#

Is that your custom class

#

Ah wait that's some lib I'm not familiar with

white citrus
#

No a db document

vale wing
#

Seems like #databases issue, provide traceback and last 3 lines of your code cause they are ones that cause the error, I'm not familiar with mongo so can't help by myself unfortunately

steep estuary
#

is there any way to delete buttons from a message in discord.py?

naive briar
#

Edit the message with the view argument set to None

#

!d discord.Message.edit

unkempt canyonBOT
#

await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the message.

The content must be able to be transformed into a string via `str(content)`.

Changed in version 1.3: The `suppress` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.

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

i want to make a command to dm server owners to inform them about new features added to my bot. theres probably not a good way to do that is there?

#

by 'good way' i mean without negatively affecting my bot in discord for sending too many dms

sterile dust
#

using the basic dm command

mighty pilot
#

yea but i dont want discord to do anything dumb for sending too many dms to new users

sterile dust
#

mh

#
@bot.command(name = "mp", aliases = ["dm","MP","DM"])
async def Mp(ctx, user: nextcord.Member = None,* , msg):
    if user == None:
        user = ctx.author
    if ctx.message.author.guild_permissions.administrator or ctx.author.id == 915096932005863464:
        await ctx.message.delete()
        try:
            await user.send(msg)
        except:
            try:
                await ctx.author.send(f"Le membre a fermé ses DMs")
            except:
                return
    else:
        await ctx.reply("Tu n'as pas la permission `Administrateur`.")
#

@mighty pilot do you want me to translate it?

#

bc its french

mighty pilot
#

no need. i know how to make the command

sterile dust
mighty pilot
#

my question was about how to avoid negative effects from sending too many dms to new users at once

#

because im sure discord watches that

sterile dust
#

just avoid it

mighty pilot
#

great idea

sterile dust
mighty pilot
#

ill prob push update notifications another way

sterile dust
#

gl

shrewd apex
#

make a mail command and keep sending messages in the mail store in db

quaint epoch
#

If you don't want to, then don't do it

mighty pilot
#

yea i think im just gonna push it to the associated servers botspam channel if they have it set for my bot. if not then they wont get an update

slate swan
mighty pilot
#

i might do that

slate swan
#

or just default to the system channel

#

but it's up to you

mighty pilot
#

for now im going to send it to the bots channel but i may add a designated updates channel if its a requested feature

toxic crown
#

Hello!
How can I get the String ' print "Hi" '?

rare echo
#

oh you are trying to eval with a discord bot?

toxic crown
#

Just want to get the String

slate swan
#

the fact that its python 2 print code lol

rare echo
#

print('Hi')

toxic crown
#

Do I need regex or something?

rare echo
toxic crown
#

Ok ok

#

I will handle it myself I guess

rare echo
#

but you are giving me a weirdly minimal amount of info

hollow crest
slate swan
#

can someone explain this error - discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range

shrewd apex
slate swan
#

thanks bro

#

hey, can anyone help me with setting discord bot? tag me in here and I will dm u

#

this is really important for me

shrewd apex
#

pWut learn to do it urself then

unkempt canyonBOT
#

@shrewd apex :x: Your 3.10 eval job has completed with return code 1.

001 | 2
002 | Traceback (most recent call last):
003 |   File "<string>", line 3, in <module>
004 | IndexError: list index out of range
shrewd apex
#

wtf

#

oh i think i pressed button by mistake

pure wadi
#

who do you guys use for your discord bot hosting?

shrewd apex
vale wing
fluid bramble
#

Hi guys, I have my bot working, but when a put it on a server it wont reply, just in private msg

naive briar
#

It needs message_content intent to access content of messages from servers

pure wadi
#

def willing to pay

naive briar
#

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

pure wadi
#

but i'm going to be launching many many bots

vale wing
pure wadi
#

nice

naive briar
pure wadi
fluid bramble
#

'Intents' object has no attribute 'message_content'

naive briar
#

Nah, even if I am, I can Google

fluid bramble
#

now im getting this error

pure wadi
#

intents = discord.Intents.default()
intents.message_content = True

naive briar
fluid bramble
#

from discord import Intents
from discord.ext import commands
from datetime import date
import calendar

naive briar
#

That doesn't answer the question

fluid bramble
#

im using replit

#

so its dowload in the time i run

slate swan
naive briar
naive briar
fluid bramble
#

[tool.poetry]
name = "repl_python3_Bot"
version = "0.1.0"
description = ""
authors = ["Your Name you@example.com"]

[tool.poetry.dependencies]
python = "^3.8"
discord = "^1.7.3"

[tool.poetry.dev-dependencies]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

naive briar
#

Bruh

slate swan
#

how can I fix that problem?

naive briar
#

Replit has a packager

#

Remove that discord package and install discord.py 2.1.0

slate swan
naive briar
slate swan
naive briar
#

What events?

slate swan
#

can we talk abt it in dms?

fluid bramble
#

bro call i can someone to share my creen?

naive briar
slate swan
#

ah I guess I didn't put client event next to on_message function

fluid bramble
#

it already worked

#

thanks

slate swan
#

ok guys I fixed it

fluid bramble
#

guys

#

what is the variable of ctx nickname of the server

naive briar
#

!d discord.ext.commands.Context.author

unkempt canyonBOT
naive briar
#

!d discord.Member.nick

unkempt canyonBOT
limpid otter
#
  @nime.error
  async def nime_error(self, ctx: commands.Context, error):
    id = await self.db.fetchval("SELECT user_id FROM users WHERE user_id = $1", ctx.author.id)
  if id is None:
    raise id("error")

i want to make my own exception if, when entering a command, the user id is not in the database?

naive briar
#

Just reply to the message?

reef vessel
#

!documentation

naive briar
#

Use check?

#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.

The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.

In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.

This function returns the **first event that meets the requirements**...
naive briar
#

That check kwarg

vale wing
vale wing
#

!d discord.on_guild_join

unkempt canyonBOT
#

discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
vale wing
#

Yeah but I'm unsure if name kwarg does automatic str cast

#

So to be safe cast it to str

#

Also for this case I recommend using @tasks.loop instead of event, as there might be suddenly many guilds adding the bot which will cause issues with channel renaming

#

You want user to reply to bot's message or smth

vale wing
#

Still explicit is better than implicit 🤗

cloud dawn
#

If there are already useless checks for it might as well use it and save some lines.

mighty pilot
#

can i make a slash command only visible to a specific server?

bright latch
#

i dont want to save the .txt in the folder just to sendpy ticket = f"ticket.txt" with open(ticket, "w") as file: async for msg in ctx.channel.history(limit=None, oldest_first=True): file.write(f"{msg.author.display_name}: {msg.clean_content}") file = discord.File(ticket) await send(file=file)

naive briar
#

discord.File's first argument accepts a path to a file or a file-like object, like io.BytesIO

#

!d io.BytesIO

unkempt canyonBOT
#

class io.BytesIO(initial_bytes=b'')```
A binary stream using an in-memory bytes buffer. It inherits [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase"). The buffer is discarded when the [`close()`](https://docs.python.org/3/library/io.html#io.IOBase.close "io.IOBase.close") method is called.

The optional argument *initial\_bytes* is a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) that contains initial data.

[`BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "io.BytesIO") provides or overrides these methods in addition to those from [`BufferedIOBase`](https://docs.python.org/3/library/io.html#io.BufferedIOBase "io.BufferedIOBase") and [`IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "io.IOBase"):
bright latch
#

ah ok but how do i not save the file i just want to send it

naive briar
#

Just pass the object in it, you can write it like a normal file

bright latch
#

how should i do that should i remove (with open)

naive briar
#

Demo:

with io.BytesIO() as fp:
    ...
    fp.write(msg.clean_content.encode())

    file = discord.File(fp, filename="meow.txt")
#

Since the io.BytesIO.write only accept a bytes object you need to encode your string

bright latch
#
        with io.BytesIO(ticket, "w") as fp:
            async for msg in ctx.channel.history(limit=None, oldest_first=True):
                fp.write(f"{msg.author.display_name}: {msg.clean_content}")
                file = discord.File(fp, filename="data.txt")
        await send(file=file)```
#

?

naive briar
#

Did you see what I sent

bright latch
#

yes

naive briar
#

Your discord.File have to be in the with block

#

And fp isn't defined

#

And you don't need to set a mode for the bytes io

naive briar
#

Remove the arguments you're giving it

#

The bytes io I mean

bright latch
#

just

#
with (ticket, "w") as fp:
            async for msg in ctx.channel.history(limit=None, oldest_first=True):
                fp.write(f"{msg.author.display_name}: {msg.clean_content}")
                file = discord.File(fp, filename="data.txt")
        await send(file=file)```
naive briar
#

I said remove the arguments

#

From the bytes io constructor

bright latch
#
        with io.BytesIO() as fp:
            async for msg in ctx.channel.history(limit=None, oldest_first=True):
                fp.write(f"{msg.author.display_name}: {msg.clean_content}")
                file = discord.File(fp, filename="data.txt")
        await send(file=file)```
#

name 'io' is not defined

slate swan
#

can someone help me with my discord bot code

#

its not working

naive briar
#

Then import it yert

slate swan
#

its too long

bright latch
#

TypeError: a bytes-like object is required, not 'str'

naive briar
naive briar
bright latch
#

fp.write(msg.clean_content.encode(f"{msg.author.display_name}: {msg.clean_content}")

naive briar
#

I

bright latch
#

now ?

naive briar
#

Okay ducky_regal see what happens

bright latch
#

dont work

naive briar
#

!d str.encode

unkempt canyonBOT
#

str.encode(encoding='utf-8', errors='strict')```
Return an encoded version of the string as a bytes object. Default encoding is `'utf-8'`. *errors* may be given to set a different error handling scheme. The default for *errors* is `'strict'`, meaning that encoding errors raise a [`UnicodeError`](https://docs.python.org/3/library/exceptions.html#UnicodeError "UnicodeError"). Other possible values are `'ignore'`, `'replace'`, `'xmlcharrefreplace'`, `'backslashreplace'` and any other name registered via [`codecs.register_error()`](https://docs.python.org/3/library/codecs.html#codecs.register_error "codecs.register_error"), see section [Error Handlers](https://docs.python.org/3/library/codecs.html#error-handlers). For a list of possible encodings, see section [Standard Encodings](https://docs.python.org/3/library/codecs.html#standard-encodings).

By default, the *errors* argument is not checked for best performances, but only used at the first encoding error. Enable the [Python Development Mode](https://docs.python.org/3/library/devmode.html#devmode), or use a [debug build](https://docs.python.org/3/using/configure.html#debug-build) to check *errors*.

Changed in version 3.1: Support for keyword arguments added.
bright latch
#

😅

#
fp.write(f"{msg.author.display_name}: {msg.clean_content}")
fp.write(msg.clean_content.encode(encoding='utf-8'))```
naive briar
#

Just

fp.write(f"{msg.author.display_name}: {msg.clean_content}".encode())```
#

JUST!?

bright latch
#

ah ok

#

thank you

#

it still save the .txt in the bot folder

naive briar
#

What's your full code now

#

Or you're just seeing the old file that's just undeleted

bright latch
#
        with io.BytesIO() as fp:
            async for msg in interaction.channel.history(limit=None, oldest_first=True):
                fp.write(f"{msg.author.display_name}: {msg.clean_content}".encode())
                file = discord.File(fp, filename="ticket.txt")
        await send(content="You Log", file=file)```
naive briar
#

Why is the file definition is in the for loop

#

It will just keep redefining

bright latch
#

what i need to do ?

naive briar
#

Just move it down?

bright latch
#

what i need to move down ?

naive briar
#

Did you read

#

Or am I just insane

bright latch
#
        with io.BytesIO() as fp:
            async for msg in interaction.channel.history(limit=None, oldest_first=True):
                fp.write(f"{msg.author.display_name}: {msg.clean_content}".encode())
            file = discord.File(fp, filename="ticket_data.txt")```
#

?

#

it does not work

naive briar
#

What does not work

bright latch
#

it works he not save

naive briar
#

But what

bright latch
#

he not send nothing

#

fp.write(f"{msg.author.display_name}: {msg.clean_content}".encode())

naive briar
#

What does that mean

hushed galleon
#

you need to seek the file pointer back to the start after you finish writing to it, otherwise dpy cant read the contents of your file

bright latch
#

he send the .txt but with nothing inside

hushed galleon
#

e.g. ```py
fp = io.BytesIO()
fp.write(b'...')
fp.seek(0)
file = discord.File(fp, ...)

upload attachment as normal```

bright latch
#

it works thanks

lost marten
#

What do you need with it?

whole sparrow
#

How do i dockerize my discord bot?

mighty pilot
#

can you put an f-string inside an f-string? having trouble with storing a message inside a database then recalling it in a way that i can mention a user. it just prints {user.mention} instead of performing the mention.

ive tried moving the {} about everywhere i can with no success. if i type the message out into the code it works flawlessly

whole sparrow
#

use python eval

lost marten
whole sparrow
#
num=10
expr="(2+(3*2))/2 + num"
print(eval(expr))
mighty pilot
sick birch
mighty pilot
#

do you have a link on docs for .format? im not too familiar with it and id like to learn more

sick birch
unkempt canyonBOT
#

@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.

hello world
mighty pilot
mighty pilot
#

thanks

mighty pilot
sick birch
#

no worries

primal token
sick birch
#

oh shut up

primal token
#

see, robin is the rudest person ever, ban him🔨

abstract kindle
#

yo, so every time I want to make changes in a file that's not a cog, I have to restart the bot, correct?

abstract kindle
#

I'm asking because I have a python file called "Class Library" which includes a bunch of classes I use throughout all of my cogs. Every time I make changes to them, I have to restart the bot for those changes to take effect. Should I just put the contents of that file in a cog so I can just reload it for the changes to go through? Should I put ALL python files (like a utils file) other than main.py in cogs so I can reload them?

glad cradle
jovial obsidian
#

how do i host a bot 24/7

pallid mango
#
@bot.command("ban")
@commands.has_permissions(ban_members=True, administrator=True)
async def ban(ctx: commands.Context, member: discord.Member) -> None:
    await member.ban()
    await ctx.send(f"Banned **{member.name}**")```
#

`Traceback (most recent call last):
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 18, in ban
await member.ban()
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/member.py", line 722, in ban
await self.guild.ban(
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/guild.py", line 3454, in ban
await self._state.http.ban(user.id, self.id, delete_message_seconds, reason=reason)
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/http.py", line 738, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

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

Traceback (most recent call last):
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions`

#

is it because i dont have missing permissions imported? or with discords.py 2.0 is it all under one import

jovial obsidian
trim shadow
jovial obsidian
#

huh

primal token
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.

primal token
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
pallid mango
#

!d discord.ext.commands.has_role

unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
pallid mango
#

it gives me missing permissions and i dont even have missing permissions in any of my commands

abstract kindle
trim shadow
#

how to check is_super_admin() or is_admin(), help me

glad cradle
glad cradle
abstract kindle
abstract kindle
pallid mango
#

guys how to unban using discord id?

trim shadow
#

hello, u can help me?

glad cradle
abstract kindle
primal token
unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

yea but instead of discord.Member i need it to unban and make the user ID as the identifier

primal token
#

Yes?

#

Not sure if that was a question or not

trim shadow
#

how to check is_super_admin or is_admin in this code? plsss

slate swan
#

i get an error saying unrxpected indentp

#

how ti fix

trim shadow
slate swan
#

let me check

#

i think whitr space

slate swan
trim shadow
slate swan
#

@trim shadow

trim shadow
slate swan
#

ok

#

@trim shadow

trim shadow
# slate swan ok

u can not "if" in like 395
like:

if ...:
  mine15 = ...
elif c = ...:
  ...
slate swan
#

wtf

#

wdym? @trim shadow

trim shadow
slate swan
#

mhm

#

why?

#

@trim shadow

trim shadow
slate swan
#

? why u delete

#

so i should do Exception("Error")

#

@trim shadow

sick birch
#

When you have a bunch of if/elif it's a sign that you should re-write or rethink code structure

#

of course the actual issue lies with indentation

trim shadow
slate swan
#

ok?

slate swan
#

bruhh

#

everything else works normally

timber kindle
#
@client.tree.command(description="Delete a mass amount of messages")
@app_commands.rename(amount="amount")
@app_commands.describe(amount="Number of Messages")
@app_commands.checks.has_permissions(manage_messages=True)
async def purge(interaction: discord.Interaction, amount: int):
  if amount == 0:
    await interaction.message.response.send_message(
    f"Amount must be more than 0",ephemeral=True)
    return
  await interaction.channel.purge(limit=amount)
  if amount == 1:
    await interaction.message.response.send_message(
    f"{interaction.user} purged {amount} message")
    return
  else: 
    await interaction.message.response.send_message(
    f"{interaction.user} purged {amount} messages")
    return```

I need help

when I run the command I get this error:
```Traceback (most recent call last):
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 263, in purge
    await interaction.message.response.send_message(
AttributeError: 'NoneType' object has no attribute 'response'

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

Traceback (most recent call last):
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'NoneType' object has no attribute 'response'
torn sail
timber kindle
#

thanks

#

It still doesn't work

#

Traceback (most recent call last):
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
wicked atlas
#

Looks like it might've taken too long for your application to respond to the interaction. It's usually good to defer the interaction as a first action, so that you can modify the response later without taking too long to respond

timber kindle
#

Idk what that means, I'm new to using interaction instead of ctx

wicked atlas
#

Have you ever seen it where a bot will show "<bot name> is thinking..."?

timber kindle
#

no

wicked atlas
#

oh

#

Well, that's what shows up when an interaction is defered

#
# defer at the beginning of your function
await interaction.response.defer()

... # do stuff

# send the response to replace the defered command's "thinking"
await interaction.followup.send("my response")
restive iron
#

Why does this block Discords heart beater?

timber kindle
# wicked atlas ```py # defer at the beginning of your function await interaction.response.defer...
@client.tree.command(description="Delete a mass amount of messages")
@app_commands.rename(amount="amount")
@app_commands.describe(amount="Number of Messages")
@app_commands.checks.has_permissions(manage_messages=True)
async def purge(interaction: discord.Interaction, amount: int):
  if amount == 0:
    await interaction.response.defer()
    await interaction.followup.send(
    f"Amount must be more than 0",ephemeral=True)
    return
  await interaction.channel.purge(limit=amount)
  if amount == 1:
    await interaction.response.defer()
    await interaction.followup.send(
    f"{interaction.user} purged {amount} message")
    return
  else: 
    await interaction.response.defer()
    await interaction.followup.send(
    f"{interaction.user} purged {amount} messages")
    return

I changed it and still get the same error

wicked atlas
#

defer as the very first thing

#

once at the very top at the function

#

That purge process probably takes a few seconds, so right now you aren't defering until after that has ended, which defeats the purpose of defering

timber kindle
#
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/ZenithBot/venv/lib/python3.8/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10008): Unknown Message

now I get this

#

I know why, I think... the command message is getting deleted?

wicked atlas
#

Yea, that would make sense, since your purging it

restive iron
#

I have the following code

import discord
from discord.ext import commands
import speech_recognition as sr

intents = discord.Intents.all()
# Create a new Discord bot
bot = commands.Bot(command_prefix='!', intents=intents)

# Define a command that allows the bot to join a voice channel and start listening for voice input
@bot.command()
async def listen(ctx):
    # Check if the bot is already connected to a voice channel
    if bot.voice_clients:
        # If the bot is already connected to a voice channel, disconnect from it
        await bot.voice_clients[0].disconnect()
    
    # Join the voice channel the user is currently in
    voice_channel = ctx.message.author.voice.channel
    await voice_channel.connect()
    
    # Start listening for voice input
    r = sr.Recognizer()
    while True:
        try:
            # Wait for the user to say something
            with sr.Microphone() as source:
                audio = r.listen(source)
                
            # Convert the voice input to text
            text = r.recognize_google(audio)
            print(text)
        except:
            print("No speech was said during this time")

# Run the bot
bot.run('My_Token')```

Why does this cause a Discord heartbeat blocked error?
wicked atlas
#

that speech recognizer and that while true loop don't look async, so they probably block the whole program and don't let it send a heartbeat ping

restive iron
slate swan
#

how to fix error indent

wicked atlas
#

dang, I responded to myself

trim shadow
#

can i use commands.Bot and app_commands together?

ebon island
#

Is it possible to detect if a user has recently had voice activity eg talking?

pallid mango
#
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.Member) -> None:

          banned_users = await ctx.guild.bans()
          member_name, member_discriminator = member.split("#")

          for ban_entry in banned_users:
              user = ban_entry.user

              if (user.name, user.discriminator) == (member_name,member_discriminator):

                  await member.unban(user)```
#

Traceback (most recent call last): File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 1349, in invoke await ctx.command.invoke(ctx) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1015, in invoke await self.prepare(ctx) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 932, in prepare await self._parse_arguments(ctx) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 839, in _parse_arguments transformed = await self.transform(ctx, param, attachments) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 709, in transform return await run_converters(ctx, converter, argument, param) # type: ignore File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/converter.py", line 1340, in run_converters return await _actual_conversion(ctx, converter, argument, param) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/converter.py", line 1222, in _actual_conversion return await converter().convert(ctx, argument) File "/home/runner/Lost-Aura/venv/lib/python3.8/site-packages/discord/ext/commands/converter.py", line 262, in convert raise MemberNotFound(argument) discord.ext.commands.errors.MemberNotFound: Member "694038289849647155" not found.

#

can someone help pleaseee?

vocal snow
#

A Member is a User who is part of a guild

pallid mango
#

oh

#

so it should be user_name, user_discriminator?

vocal snow
#

Those are just variable names

#

You should use UserConverter instead of MemberConverter

#

You can typehint the parameter to discord.User instead

pallid mango
#
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.User) -> None:

          banned_users = await ctx.guild.bans()
          member_name, member_discriminator = member.split("#")

          for ban_entry in banned_users:
              user = ban_entry.user

              if (user.name, user.discriminator) == (member_name,member_discriminator):

                  await member.unban(user)```
#

because that would change anything that is labeled member to discord.User right

torn sail
pallid mango
#

yes but i wanna unban using user id

trim shadow
#

hello, i need example hybird command, plsss

slate swan
slate swan
pallid mango
#

wait so

#

i mean like "663517633978564628" this id

slate swan
#

Kind of easy,
What we did here?
Well we are checking if # is in the member argument or not of there then it will ban according to the name if not there it will get the user with user id

pallid mango
#

okay

slate swan
#

#other codes i mean u can directly now do
if (member.name, member.discriminator)==(user.name, user.discriminator):

#

@pallid mango u can do kind of like dat

#

No need of
member_name and member_discriminator while doing with id

#

Altho ur code is kind of old tho 🌚

#

U can use...

pallid mango
#

and now im like super confused i tried reading the docs but got overwhelmed

slate swan
#

Xd

pallid mango
#

i would imagine all of my code is old

slate swan
#

Ahh

slate swan
#

I had to change the whole code

#

!d discord.Guild.unban

unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

@pallid mango easiest way to do

#

user=bot.get_user(id)
await guild.unban(user=user, reason=None)

pallid mango
#

guild is unidentified

#

i sent u a dm spooky

torn sail
#

And it will work with user#1234

slate swan
torn sail
#

!d discord.ext.commands.UserConverter

unkempt canyonBOT
#

class discord.ext.commands.UserConverter(*args, **kwargs)```
Converts to a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

All lookups are via the global user cache.

The lookup strategy is as follows (in order)...
slate swan
#

It will be ctx.guild since u using prefix

pallid mango
#
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.User) -> None:
      user=bot.get_user(id)
      await ctx.guild(user=user, reason=None)```
slate swan
#

Ye this should work

pallid mango
#

okay

slate swan
#

Nah nah

#

user=bot.get_user(member)

#

💀

#

If u use id

torn sail
slate swan
torn sail
#

Yep

slate swan
#

Cul

pallid mango
#
@bot.command("unban")
@commands.has_any_role("Founder","Leader","Recruiter")
async def unban(ctx: commands.Context, member: discord.User) -> None:
    await ctx.guild.unban(member, reason=None)
    await ctx.send(f"Unbanned **{member.name}**!")```
slate swan
#

Yes

#

Should work

pallid mango
#

okay now how do i delete message after a little bit of time

#

like 10 seconds or something ik its super simple before update but idk now

slate swan
#

await ctx.send(...., delete_after=10)

pallid mango
#

okay

slate swan
#

!d discord.ext.commands.Context.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.

This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.

For interaction based contexts this does one of the following...
pallid mango
#

bet

#

also next question

slate swan
#

Ye

pallid mango
#
@bot.event
async def on_member_join(member):
  if member.guild.id != 1050564778361364530: return
  welcome = bot.get_channel(1050564779493826570)
  await welcome.send(f"Hello, {member}, welcome to Ace Public.")
  await member.add_roles("Fans")```
#

can i have this bot control two different welcome channels server to server

slate swan
#

Database

pallid mango
#

because its in both of my servers and the two servers correlate with one another or do i need a whole new bot

#

nope not me, whole new bot 🙂

slate swan
#

!d discord.Member.guild

unkempt canyonBOT
slate swan
#

Oh cool

pallid mango
#

well i mean like on join just send a welcome message

slate swan
pallid mango
#
@bot.event
async def on_member_join(member):
  if member.guild.id != 1050564778361364530: return
  welcome = bot.get_channel(1050564779493826570)
  welcome1 = bot.get_channel(1050570584817418380)
  await welcome.send(f"Hello, {member}, welcome to Ace Public.")
  await welcome1.send(f"Hello, {member}, welcome to Ace Private.")
  await member.add_roles("Fans")
  await member.add_roles("ACE")```
#

would need two different events right?

slate swan
#

I prefer using database 💀

pallid mango
#

and then the add roles

slate swan
#

Kind of like that

#

To get the guild name

pallid mango
# slate swan Yes
@bot.event
async def on_member_join(member):
  if member.guild.id == 1050564778361364530: return
  welcome = bot.get_channel(1050564779493826570)
  welcome1 = bot.get_channel(1050570584817418380)
  await welcome.send(f"Hello, {member}, welcome to Ace Public.")
  await member.add_roles("Fans")
  elif member.guild.id == 1050570584280531065:
  await welcome1.send(f"Hello {member}, congratulations, welcome to Ace Clan!")
  await member.add_roles("ACE")```
#

okay so i know the elif is wrong

slate swan
#

Ur indention is wrong

pallid mango
#

yea id say so

slate swan
#
@bot.event
async def on_member_join(member):
  if member.guild.id == 1050564778361364530: 
   welcome = bot.get_channel(1050564779493826570)
  
   await welcome.send(f"Hello, {member}, welcome to Ace Public.")
   await member.add_roles("Fans")
  elif member.guild.id == 1050570584280531065:
   welcome1 = bot.get_channel(1050570584817418380)
   await welcome1.send(f"Hello {member}, congratulations, welcome to Ace Clan!")
   await member.add_roles("ACE")```
pallid mango
#

ohhh

#

i could barely even see the difference on my monitor

#

everything look good on that one?

slate swan
#

Ofc

#

I just gave some spaces 💀

#

I mean just indented the code

pallid mango
#

do you know how to fix this keep_alive this for replit

slate swan
#

I am on mobile so, it's possible to lil things go wrong

pallid mango
#

i dont know of a better alternative

slate swan
#

To make bot 24/7

pallid mango
#

yea everytime i set it up it just says too many requests

slate swan
#

🤷

pallid mango
#

oooh i wonder if i need to use keep_alive if i have replit+ where it gives an option to run 24/7

slate swan
#

Nah nah

#

keep_alive is a function

#

Remove it 💀

#

If u don't understand

pallid mango
#

oh

#

okay i removed it

slate swan
#

Nice 🙂

slate swan
#

guys how long have you been learning python and started coding py bots

rare echo
slate swan
#

Me only 2 years approx 💀💀

#

1 year or dc bot coding 💀💀💀

torn sail
#

I Started discord bots way too early

slate swan
#

bro that early

#

i am barely learning from 7 months and in 3-5 months will earn all advance python and start to learn about coding bots

#

and then i wanna learn Lua too.

#

btw i am still a school today 💀

#

lua is meh

#

all i can imagine doing with lua is roblox plugins rn

cold sonnet
#

I didn't learn any python before coding bots

cold sonnet
slate swan
cold sonnet
slate swan
slate swan
shy kelp
#
import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.message_content = True
intents.members = True

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

@bot.event
async def on_ready():
    print('Ready!')
    
@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)

bot.run(TOKEN)
#

can someone explain why this just does not work

#

when i type the command nothing happens

slate swan
#

If your token correct?

#

And is ur intents enabled in developer portal?

shy kelp
#

yea token is correct and how do i enable intents in portal?

slate swan
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.

This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.

This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.

Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.

async with x Asynchronously initialises the bot and automatically cleans up.

New in version 2.0.
shy kelp
#

is it this? its on

slate swan
#

Ye

#

Maybe ur token is incorrect then

#

Cuz as far as I see it's nok

rare echo
#

is your token “ “?

shy kelp
#

no token is correct other other stuff is working in the code

slate swan
#

Show full code

#

Do u have on_message event?

#

!host

shy kelp
#
import discord
from discord.ext import commands

intents = discord.Intents.all()
intents.message_content = True
intents.members = True
redx = 280351437203177483
small_pp = 768589770343317536
bot_test_id = 1046566076831514634

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

@bot.command()  
async def test(ctx, arg):
    await ctx.send(arg)

@bot.event
async def on_presence_update(before, after):
    if before.guild.id == 768589770343317534:
        print(after.name)
        print(after.status, "\n")

        if after.id == redx and before.status == discord.Status.offline and after.status == discord.Status.online:
            print("Redx is Online")
            await bot.get_channel(small_pp).send("https://tenor.com/view/online-isaiah-gif-22767935")

        if after.id == redx and before.status == discord.Status.online and after.status == discord.Status.offline:
            print("Redx is offline")
            await bot.get_channel(small_pp).send("https://tenor.com/view/offline-isaiah-gif-22767927")

@bot.event
async def on_message(message):
    print(message.author.name, message.content, message.channel.id, message.guild.name)
    server = bot.get_guild(bot_test_id)

    if message.content.lower() == "!owner":
        owner = server.owner

        await message.channel.send(f"The owner is {owner.mention}.")
    
    if message.content.lower() == "!hello":
        await message.channel.send(f"Hi {message.author.mention}!")

    if message.content.lower() == "!":
        print("hi")
    
    

@bot.event
async def on_ready():
    print('Ready!')
    

bot.run(TOKEN)

rare echo
#

i just had a stroke reading that

slate swan
#

Yes u have this problem

rare echo
#

for the host guy ^

slate swan
#

@bot.event
async def on_message(message):
await bot.process_commands(message)

#

Do it @shy kelp

shy kelp
#

sure

#

what does that do?

slate swan
#

It will process the message evnt

#

And let the prefix commands work too

#

If u don't process it, prefix commamds won't work

shy kelp
#

i put it in and the test command still wont work

#

all commands dont work but events do

slate swan
slate swan
#

async def on_message(message):
await bot.process_commands(message)
if before.guild.id.....
#start from here

slate swan
shy kelp
#

i do

slate swan
#

it saves you from adding an extra process_commands line

#

Oh thats cul

shy kelp
#

ill add ur thing to mine

slate swan
#

I thought listen only works when u have 2 events 💀

#

@slate swan thanks xd

#

Still ur pfp ducky_sus

shy kelp
#

its working now that i added it the the other on_message but whats .listen() ?

slate swan
#

@bot.listen()
async def on_message(message):

#

Instead of @bot.event

shy kelp
#

is it just a substitute for .event ?

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")

The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").

Example...
torn sail
slate swan
#

U can't have 2
on_message main event so only the last on_message event wilk be called

#

If u use @bot.listen()
Then it will still listen on both of on_message evnt

shy kelp
#

ohh

#

wil that work for 3 or more of the same event?

slate swan
slate swan
slate swan
slate swan
#

\🍑

#

😂

#

sus

#

thats a joke, dare

#

Ik 💀

#

Can I use website hosting service to host my discord bot?

rare echo
slate swan
rare echo
#

i mean if you dont need a console and just STDOUT you can use smth like pebble for like $2

#

or an old laptop, raspberri pi for one time purchase host

slate swan
#

just use oracle, its free forever

#

need a credit card or debit card for verification tho

rare echo
slate swan
#

https://paste.pythondiscord.com/cehecifohe

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 658, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1524, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 940, in invoke
    await self.prepare(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 874, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 780, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 624, in transform
    return await run_converters(ctx, converter, argument, param)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1268, in run_converters
    return await _actual_conversion(ctx, converter, argument, param)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1180, in _actual_conversion
    raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
nextcord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "level".```
naive briar
#

The library cannot convert the first argument you gave it to int

#

How did you invoked the command

slate swan
#

wdym invoked

naive briar
#

Call

slate swan
#

like from a group

slate swan
#

what did you type on discord to run that command

#

i dont rrlly understand the question

shy kelp
#
async def poll(message, x, y):
    embed = discord.Embed(title="Poll", description=f"React with 1 for {x} or react with 2 for {y}", color=0xFF0000)

    msg = await message.channel.send(embed=embed).add_reaction(1050671368968081459)```

The number in the add_reaction bracket is the id for the 1️⃣ emoji

i get this long error
slate swan
#

just use .add_reaction(":one:")

lost marten
#

You can't chain coroutines

#
await (await message.channel.send(...)).add_reaction(...)

Should work i think

slate swan
lost marten
#

But the second is accurate

slate swan
#

and you can't use the returned Message object again unless you also shove a walrus operator in there.

lost marten
#

That's true

slate swan
#

is 1gb enough for a discord bot?

upbeat gust
#

What does it do, how many servers

slate swan
upbeat gust
#

and first question?

slate swan
#

prob around has 80-90 commands or less or more

upbeat gust
#

Eh you could just start with one and see how it goes

#

Upgrade if needed later

slate swan
glad cradle
#

maybe you could use this approach when you're in production, when you have a sharded bot and you don't want to wait hours to get the Bot back online on some servers (though idk if this would work)

slate swan
#

depends on what kind of changes

#

usually you can use extensions

#

they are not meant to be used only with cogs

glad cradle
#

ik

#

but he's using modules

#

imported in cogs

slate swan
#

https://paste.pythondiscord.com/cehecifohe

Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\client.py", line 502, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\Aleccy Bot\main.py", line 658, in on_command_error
    raise error
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\bot.py", line 1382, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 1524, in invoke
    await ctx.invoked_subcommand.invoke(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 940, in invoke
    await self.prepare(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 874, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 780, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 624, in transform
    return await run_converters(ctx, converter, argument, param)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1268, in run_converters
    return await _actual_conversion(ctx, converter, argument, param)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\converter.py", line 1180, in _actual_conversion
    raise BadArgument(f'Converting to "{name}" failed for parameter "{param.name}".') from exc
nextcord.ext.commands.errors.BadArgument: Converting to "int" failed for parameter "level".```
peak pewter
#
@client.event
async def on_member_join():
    await discord.Member.add_roles(discord.utils.get(discord.guild.roles, name = "member"))
#

This is not working

#

@glad cradle

slate swan
#

on_member_join(member):
await member.add_roles(....)

timid spade
placid verge
#

How can I find out if a message was sent 30 minutes ago or not?

naive briar
unkempt canyonBOT
#

@discord.ui.select(*, cls=<class 'discord.ui.select.Select'>, 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.
naive briar
#

The options kwarg

timid spade
#

i added options like this

slate swan
unkempt canyonBOT
slate swan
#

subtract it from current time to get a timedelta

slate swan
#

!d discord.ui.Select

unkempt canyonBOT
#

class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.

New in version 2.0.
timid spade
#

ok let me try

placid verge
#

I don't know how to work with timestamps

vale wing
#

!d datetime

unkempt canyonBOT
#

Source code: Lib/datetime.py

The datetime module supplies classes for manipulating dates and times.

While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.

vale wing
#

!d discord.utils.utcnow

unkempt canyonBOT
#

discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.

This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "(in Python v3.11)") since it is an aware datetime, compared to the naive datetime in the standard library.

New in version 2.0.
naive briar
#

!d discord.utils.utcnow

slate swan
#

Yo

naive briar
#

Bruh

#

I misread it

slate swan
#

discord.utils.make_a_bot() when

#

💀💀💀

#

Imagine if this would exist

#

for uptime? you can just store the datetime at which bot was launched

slate swan
placid verge
#
Traceback (most recent call last):
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 169, in _loop
    await self.coro(*args, **kwargs)
  File "C:\Users\imac\IdeaProjects\Moamele\me\Moamele\net\main.py", line 637, in channelmanager
    message = await channel.fetch_message(channel.last_message_id)
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1686, in fetch_message
    data = await self._state.http.get_message(channel.id, id)
  File "C:\Users\imac\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 366, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_id: Value "None" is not snowflake.
vale wing
# slate swan discord.utils.make_a_bot() when
import asyncio
from discord.utils import make_a_bot


async def main():
    await make_a_bot(" free dollar generator no fbi".strip().title().beautify().fontify().vectorize())

asyncio.run(main())```
#

The future of IT

vale wing
#

Read docs, it's optional

#

!d discord.TextChannel.last_message_id

unkempt canyonBOT
placid verge
placid verge
#

it even prints the time diff

#
msg_time = message.created_at
            time = utcnow()

            diff = time - msg_time
            print(diff)
ebon island
# torn sail In discord.py, I don’t think so

The way you phrased this implies that other languages/frameworks do have this capability, Is that true? If so, which language/framework is the best at present and how might I compare the quality of implementation in the various languages?

glad cradle
#

!d disnake.on_voice_state_update

unkempt canyonBOT
#

disnake.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://docs.disnake.dev/en/latest/api.html#disnake.Member "disnake.Member") changes their [`VoiceState`](https://docs.disnake.dev/en/latest/api.html#disnake.VoiceState "disnake.VoiceState").

The following, but not limited to, examples illustrate when this event is called...
mighty pilot
#

With the new server subscription bs do you guys expect an update to discord.py and the forks to be coming?

slate swan
#

if the api will support that for bots, each Library will implement it.

flint storm
#

does anyone know which library to use to make telegram bots?

slate swan
flint storm
#

thank u

torn sail
#

However voice receiving is an undocumented feature

#

Oop snipy already said that

slate swan
#

async def coins(interaction: discord.Interaction, user: discord.Member = commands.Author):

is there any error ?

naive briar
#

What does commands.Author even mean

slate swan
#
  • this code was already given to me by someone in this server, and it was working
#

but with no slash commands

#

@naive briar any help ?

primal token
slate swan
#

This works

primal token
#

Your annotation is not correct?

slate swan
#

but this doesn't

primal token
primal token
slate swan
#

i commented it to try the other command

slate swan
#

its a part of prefix command extension

#

interaction.user

#

yes^

#

!d discord.Interaction.user

unkempt canyonBOT
slate swan
#

you'll have to do it inside your command function

#

it's with the parameters , it will be definied with the interaction at the same time

slate swan
#

simple as that.

#

hmmm i'll try

#

U can use discord.Interaction.user too maybe

#

as this ?

#
  File "C:\Users\user\Desktop\Other\Bots_For_Sell\GameOver bot\bot.py", line 31, in <module>
    async def coins(interaction: discord.Interaction, user:None):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 889, in decorator
    command = Command(
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 685, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 393, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 832, in annotation_to_parameter
    (inner, default, validate_default) = get_supported_annotation(annotation)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\transformers.py", line 791, in get_supported_annotation
    raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'NoneType'>```
#

user=None 🙂

#

It will be that not with colon

slate swan
#

spooky smart

#

it will be definied as None always

slate swan
slate swan
#

it will work

#

everyone uses the same

#

Altho without defining it if we just mention the member it should catch the object automatically isn't it?

#

I think so

#

as this ?

#

Yes

unkempt canyonBOT
#

examples/app_commands/basic.py lines 69 to 76

# or you can mark it as Optional from the typing standard library. This example does both.
@client.tree.command()
@app_commands.describe(member='The member you want to get the joined date from; defaults to the user who uses the command')
async def joined(interaction: discord.Interaction, member: Optional[discord.Member] = None):
    """Says when a member joined."""
    # If no member is explicitly provided then we use the command user here
    member = member or interaction.user```
timid spade
slate swan
#

OHH WAIT in slash command u MUST define the shits

#

I foegot 💀💀

slate swan
slate swan
#

🤷

#

@slate swan i want to say i love you but i'm not gay hhhhhhhh

slate swan
slate swan
timid spade
#
class Role_Select(Select):

    def __init__(self) -> None:
            super().__init__(max_values= max_val,min_values=min_val ,options=[discord.SelectOption(label='hm')])

    async def callback(self, interaction):
        user = interaction.user
        await interaction.response.send_message(":arrows_clockwise: Thinking....", ephemeral = True)
        await interaction.delete_original_response()
        for item in roles:

            role = get(ctx.guild.roles, name= item)
            if item in self.values and role not in user.roles:
                await user.add_roles(role)

                
            elif role in user.roles and item not in self.values:
                await user.remove_roles(role)
slate swan
slate swan
slate swan
slate swan
slate swan
#

@unkempt canyon yo ded guy

#

4k forks means ...

#

4k libraries??? xd

timid spade
slate swan
#

It's not good way to add select options xd

slate swan
#

thats how git works

slate swan
timid spade
timid spade
#

i cant spot the error 🫠

weary copper
#

does anyone know how to check my bot's permissions in my script?

#

i'm trying to check if I have manage_emojis permissions (which I should), but discord.Permissions.manage_emojis but it's just giving <flag_value flag=1073741824>

#

bot.Permissions doesn't seem to work - i think I'm misunderstanding the documentation