#discord-bots

1 messages Β· Page 1 of 1 (latest)

slate swan
#

mhm

#

display_avatar

#

no need to be sorry lol

#

interactions use webhooks so maybe that?

#

The interaction token is invalidated so yea

#

Maybe your bot is taking too much time to respond to the interaction... Maybe

#

Try deferring it

#

No idea for nextcord. I've only used dpy

terse coyote
#

i need to check if bot top role > member top role.
how?

slate swan
#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
slate swan
#

for dpy, yes

#

Then it's same

terse coyote
#

I tried this:

if self.client.top_role.position < member.top_role.position:
slate swan
#

Defer it in start and do whatever you want to process in your command and respond with a followup

tough lance
#

hi

gilded gust
#

Help please

#

ok, thanks

#

will try

slate swan
tough lance
#

there must be something like interaction.followup

terse coyote
#

when i use command with this check the whole command fails
without - ok

terse coyote
#

hm..

slate swan
unkempt canyonBOT
#

property me```
Similar to [`Client.user`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.user "discord.Client.user") except an instance of [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member"). This is essentially used to get the member version of yourself.
gilded gust
tough lance
unkempt canyonBOT
#

The position of the role. This number is usually positive. The bottom role has a position of 0.

Warning

Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.

slate swan
gilded gust
#

becuase i dont know how to pycord lmfao

tough lance
#

me neither

#

But what's the code?

slate swan
#

Uhh so you responded normally to an interaction but now needs to respond again.. right?

#

There's a followup webhook you can use

#

But iirc you need to defer your response or something like that to use it otherwise it's interaction token will be invalidated

tropic burrow
#

why does my bounty command not work. the rounded value IS printed but no embed is sent

@client.command()
@commands.cooldown(1,10,commands.BucketType.user)
async def bounty(ctx):
  worth = random.randint(1000,100000)
  rounded = str(round(worth,-3))

  print(rounded)
  if bounty <= 10000:
    mbed1 = discord.Embed(
      title="noob monke. imagine low bounty",
      description=f"{ctx.author} is worth {rounded} monkeybux!"
    )
    await ctx.send(embed=mbed1)
   
  elif bounty >= 10000:
   mbed2 = discord.Embed(
     title="u are good but not enough to be pro monke",
     description=f"{ctx.author} is worth {rounded} monkeybux!"
   )
   await ctx.send(embed=mbed2)
  elif bounty >= 50000:
    mbed3 = discord.Embed(
      title="pro monke, must've done some bad things to get this bounty",
      description=f"{ctx.author} is worth {rounded} monkeybux!"
    )
    await ctx.send(embed=mbed3)
  elif bounty >= 75000:
    mbed4 = discord.Embed(
title="damn, certified pro monke. I wonder what you did to have such a bounty",
      description=f"{ctx.author} is worth {rounded} monkeybux!"
    )
    await ctx.send(embed=mbed4)
  elif bounty == 100000:
    mbed5 = discord.Embed(
      title="OUR LORD AND SAVIOR.  WE SHALL MAKE A CREW AFTER YOU: MONKE PIRATES. WE SHALL PROTECC DA CAPTAIN!!!",
      description=f"{ctx.author} is worth {rounded} monkeybux!"
    )
    await ctx.send(embed=mbed5)
slate swan
#

because bounty -> function

#

Also your if elif statements doesn't seem correct. A value of 75000 will be responded 3 times with the embed of 10000

tropic burrow
tropic burrow
slate swan
#

!e ```py
bounty = 75000

if bounty <= 10000:
print(1)
elif bounty >= 10000:
print(2)
elif bounty >= 50000:
print(3)
elif bounty >= 75000:
print(4)
elif bounty == 100000:
print(5)

unkempt canyonBOT
#

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

2
slate swan
#

Got it?

slate swan
tropic burrow
#

oh im blind*

slate swan
slate swan
slate swan
#

Just gotta wait for discord to fix it or revert the changes

slate swan
#

Hi everyone. There is currently an issue being investigated with interaction edits, deletes, and followups. This issue results in receiving 50027: Invalid Webhook Token errors when trying to edit, delete, follow up, or take some other actions on interaction webhooks.

terse coyote
#

how to get command message and delete it?

paper sluice
#

if its a prefix command, you can get it using ctx.message

slate swan
#

!d discord.ext.commands.Context.message ?

unkempt canyonBOT
#

The message that triggered the command being executed.

Note

In the case of an interaction based context, this message is β€œsynthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.

hasty loom
#

bot loads up fine and stuff but the commands arent coming and jishaku also isnt recognized

slate swan
#

setup_hook outside the class

hasty loom
#

so if i do this it still wont work

slate swan
#

await bot??.load_extension

hasty loom
slate swan
# hasty loom what

Uh maybe it's correct but you can just use self.load_extension I guess

#

Also iirc it's non-asynchronous method

hasty loom
#

yeah it is but like when i restarted my bot after like a year it kept screaming at me that its not

slate swan
#

!d discord.ext.commands.Bot.load_extension

unkempt canyonBOT
#

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

Loads an extension.

An extension is a python module that contains commands, cogs, or listeners.

An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.

Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine "(in Python v3.10)").
slate swan
#

Yes it is

#

Changed in 2.0

devout iris
#
PS C:\Users\Administrator\Desktop\Flly Bot> & C:/Users/Administrator/AppData/Loc
al/Programs/Python/Python39/python.exe "c:/Users/Administrator/Desktop/Flly Bot/
main.py"
Traceback (most recent call last):
  File "c:\Users\Administrator\Desktop\Flly Bot\main.py", line 249, in <module>
    bot.run(TOKEN)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 715, in run
    return future.result()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 694, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 658, in start
    await self.connect(reconnect=reconnect)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 599, in connect
    raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000084A8B29430>
Traceback (most recent call last):
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
PS C:\Users\Administrator\Desktop\Flly Bot>
#

what is that?

limber bison
#
import discord

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

client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')

client.run('xxx')```
#

is it ok ?

#

error in 3rd line

#

πŸ€”

slate swan
devout iris
hasty loom
#

have no idea whats wrong

slate swan
#

error?

#

i'll also suggest to name folders with characters like -, use an underscore instead ( tho its irrevalent here)

hasty loom
slate swan
shrewd apex
#

why else would the name their cog folder slash cog πŸ’€

slate swan
#

cause yes

hasty loom
#

yep lol

#

wait whAT

#

WHY IS IT NOT USING V2 WHAT THE HELL

slate swan
shrewd apex
#

πŸ’€

hasty loom
#

IVE BEEN DEBUGGINF THIS FOR 3 HOURS

slate swan
#

thats why you don't keep multiple versions of python

hasty loom
#

WAIT NO I DIDNT DO THE SOURCE COMMAND

shrewd apex
#

u have Ultron in ur system then

slate swan
#

yeah ..

hasty loom
#

hhaahaha programming is my favourite past time hobby Hahahah

slate swan
shrewd apex
#

πŸ’€

slate swan
#

.

#

Do assert discord.__version__.startswith('2'), "run the source command dude"

#

Always helped me to remember to turn on venv πŸ˜”

hasty loom
#

yoo at least i know that my cog got loaded

slate swan
#

imagine your linter not shouting

slate swan
#

I code in notepad

#

vim when

hasty loom
slate swan
#

my bot.py is 421 lines now, gotta remove 1 cause funny

#

you're funny overall so no

shrewd apex
#

πŸ’€

slate swan
#

Make a language to code using only special numbers

#

new startup idea

hasty loom
#

also anyone know how to tell me which line number the error is in the actual file of the cog

slate swan
#

dont await the sync ig

#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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

Syncs the application commands to Discord.

This must be called for the application commands to show up.
slate swan
#

2-3 line

slate swan
slate swan
dusky pine
#

it's in file_name:line_num format

slate swan
#

!d discord.ext.commands.Bot.add_cog is async too

unkempt canyonBOT
#

await add_cog(cog, /, *, override=False, guild=..., guilds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Adds a β€œcog” to the bot.

A cog is a class that has its own event listeners and commands.

If the cog is a [`app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group") then it is added to the bot’s [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") as well.

Note

Exceptions raised inside a [`Cog`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog "discord.ext.commands.Cog")’s [`cog_load()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Cog.cog_load "discord.ext.commands.Cog.cog_load") method will be propagated to the caller...
shrewd apex
slate swan
#

loooli i wish this will make people stop importing the cogs and adding them in their main file

slate swan
hasty loom
#

FINALLY

#

i think i just need sleep i lost my ability to read

dusky pine
shrewd apex
#

πŸ‘

terse coyote
#

how to get member for unban?

quaint zodiac
#

hi

slate swan
hasty loom
slate swan
unkempt canyonBOT
#

class discord.Object(id)```
Represents a generic Discord object.

The purpose of this class is to allow you to create β€˜miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.

There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.

x == y Checks if two objects are equal.

x != y Checks if two objects are not equal.

hash(x) Returns the object’s hash.
shrewd apex
slate swan
#

no ew

#

i'd rather perform an invalid unban operation than fetching the ban list and checking if the user is actually banned or not

shrewd apex
#

y?

slate swan
#

same amount of requests, less pain

shrewd apex
#

what ever suits u Β―\_(ツ)_/Β―

dusky pine
slate swan
#

lol yes

dusky pine
#

i know your every moves

#

😈

slate swan
#

not really

shrewd apex
slate swan
#

i dont use lightbulb anylonger, made my own command hander lip_bite

dusky pine
#

Grrrrrr

#

my predictions were incorrect

#

so uhh.... move to djs?

slate swan
#

nah

#
import hikari

import dawn

ext = dawn.Extension("extension")


@ext.listen_for(hikari.MessageCreateEvent)
async def event_example(
    event: hikari.MessageCreateEvent,
) -> None:  # NOTE: this does not support annotated event
    print("Message created.")  # mention the event class in the decorator.


@ext.register
@dawn.slash_command()
async def ping(ctx: dawn.SlashContext) -> None:
    await ctx.create_response("pong!")


def load(bot: dawn.Bot) -> None:
    ext.create_setup(bot)
``` totally not inspired from lightbulb
dusky pine
#

is it named after pydis' mod dawn?

slate swan
#

hikari - light
dawn - time at which first light appears in sky

dusky pine
#

cool

cold tide
#
	while True:
		time.sleep(0.2)
		random.choice(userr)
		embed.add_field(name="Avaliable User βœ…",value=random.choice(userr),inline=True)
		await ctx.reply(embed=embed)``` can anyone fix this issue, it adds on more random.choices to the embeded
slate swan
#

you want it to be same for all the replies?

cold tide
#

Everytime i run !user it adds on more users.

#

I only want one to be chosen.

slate swan
#

!e ```py
import random
a = [1,3,4,5]
for _ in range(2):
print(random.choice(a))

#

!e ```py
import random
a = [1,3,4,5]
var = random.choice(a)
for _ in range(2):
print(var)

unkempt canyonBOT
#

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

001 | 1
002 | 1
cold tide
#

Okay thankyou!

slate swan
dusky pine
#

new kid = cool

slate swan
#

they just didnt implement any fancy abstractions, everything's native and accords to the raw discord API

slate swan
shrewd apex
#

kiba gonna be sed πŸ˜”

slate swan
#

That's my most beginners (in python) does not prefer hikari

#

i mean thats good isnt it, let dpy bare all that headache

cold tide
#

Exact same issue.

slate swan
cold tide
#

Says await outside of function

#

@bot.command() async def user(ctx): embed=discord.Embed() a = ["sicud","qiied","iwudj","7w8xi"] var = random.choice(a) for _ in range(2): embed.add_field(name="Avaliable User βœ…",value=random.choice(a),inline=True) await ctx.reply(embed=embed)

slate swan
#

did you save and rerun?

#

You don't just copy and paste the stuff..? Try to understand what they meant

cold tide
#

Yes

slate swan
#

You're still doing same value=random.choice

#

and you are still not using the variable i declared for the value kwarg

#

and for loop is outside the function

terse coyote
#

how to unban by id?

slate swan
#

await Guild.unban(discord.Object(id=id))

slate swan
# terse coyote how to unban by id?

bot = commands.Bot(...)

@bot.command()
#add permissions
async def unban(ctx: commands.Context, user_id: int) -> None:
  await ctx.guild.unban(discord.Object(user_id))

pepe_exit

terse coyote
#

thx❀️

placid willow
#

How bad is the idea of having cogs as separate repos in a GitHub org and link them back to the main bot with submodules tracking the master branch of the cogs

slate swan
placid willow
#

"Because I want it" is one

slate swan
#

πŸšΆβ€β™‚οΈ or not wtf

placid willow
slate swan
placid willow
#

Can you elaborate?

#

The first part I can understand: Lotsa .git means more space consumed. But not quite the second

slate swan
#

how are you planning to load that cogs then

#

clone the repo, copy the path and load it?

glossy ruin
#

how is some bot seeing git commits

slate swan
glossy ruin
#

yeah

slate swan
placid willow
glossy ruin
#

is there any api for it? to get stuffs from github?

#

i want to do it myself πŸ™‚

slate swan
glossy ruin
#

ok thanks lemon_happy

placid willow
slate swan
placid willow
#

Ah screw it. It's possible, yes?

slate swan
#

yeah~

#

if you still persist on using another repo, you could've used bot.load_extensions_from() as well because it loads all the extensions in the directory ( except the ones with _ in the start )

terse coyote
#

how to check user in ban or no?

slate swan
slate swan
unkempt canyonBOT
#

async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").

You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to get this information.

Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.

Examples

Usage...
terse coyote
#

Why don't I get errors in cogs?

terse coyote
slate swan
terse coyote
# slate swan Wym

Let's say I have an error in embed, I didn't write description, but somehow differently. In this case, I don't have an error.

slate swan
terse coyote
#

no

#

hm...

slate swan
dusky pine
#

description is not required

#

you can just have embed with only title

slate swan
#

you can even have embeds without titles mmLul

slate swan
#

Q; not at home at mo and on my phone. Am I correct in thinking I need to create an app on reddit in order to get like random images, posts, etc from what ever subreddit I add in my code? A few people seem to say you do where others dont.

#

Yes and no, not necessarily

slate swan
#

You can just make a request to https://reddit.com/r/<subreddit>.json

#

or that

#

If you use a library like Praw (I think it's that) it will require you to bave an app on Reddit, kind of overkill depending on what you want

#

Discord: "everyone, move to slash commands"
Also Discord when they break: "imma just quietly wait for people to start their day"

#

kek fr

#

They haven't called any engineers to fix the issue

#

Ok cheers much appreciated, worked with apis in terraform/ansible so should be OK, I'll look at the json one too see which one I can get working... Thank you!

#

They're just waiting for them to come and start their day Dead

sick birch
slate swan
#

ah well

#

Discord's issue is related to the snowflakes getting a new digit

#

Kind of expected at this point and even predicted it yesterday

#

Discord after all

#

They had 7 years to prepare for that..

brazen raft
#

Any idea why setup_hook doesn't get called?

sick birch
brazen raft
#

I subclassed discord.ext.commands.AutoShardedBot (discord.py version 1.7.3)

#

What code do you need to see?

#

It's an asynchronous method I've overridden in my subclass

#

I have also overridden run:

def run(self) -> None:
    print("Ran run()")
    super().run(os.getenv("DISCORD_BOT_SECRET"), reconnect=True)
#

The print works and the bot runs

#

It just doesn't respond to messages because I've made it so it returns in on_message if a database connection was not made

#

setup_hook is supposed to setup a database connection

#

But setup_hook simply doesn't get called

#

At least so it seems

sick birch
#

setup_hook is a feature of v2.0.0^

ivory wraith
#

hey I have a pretty simple question, but I can't seem to figure interactions (specifically buttons) out with discord.py, could someone tell me how they work?

left vector
#

is there any way for my bot to delete all messages with the selected word
like.. delete past messages also

slate swan
#
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\channel.py)

anyone know how to fix this?
Recently I uninstalled and installed discord.py module, and after I reinstalled it, this error has been coming up every time I run a discord bot

sick birch
ivory wraith
#

thanks so much!

whole sparrow
#

Is there any easy method of doing pagination?

#

Like an external module that could work with disnake? or like an example code

slate swan
unkempt canyonBOT
slate swan
#

Or make your own paginator plugin

whole sparrow
#

Oo ill have a look at that

slate swan
pastel ridge
#

hello

#

I need help with an exercise

#

can someone help me?

shrewd apex
#

how do we help if u don't tell what the exercise is

pastel ridge
#

well

#

if you know keystroke dynamics?

placid verge
#

how can i deselect the selected value in menus using discord.py?

slate swan
pastel ridge
#

i must use python to make features about txt files

#

i want to read txt files with python

#

and make some calculations

#

about duration

placid verge
shrewd apex
#

or rather the old view

placid verge
placid verge
#

I want that tick to be removed

pastel ridge
#

???

warm tulip
#

Halo

#

Hello*

#

How j can make a cmd that ads bot to a voice and never leaves voice till his online?

maiden fable
slate swan
maiden fable
#

There u go

#

The latest version is 2.0 (still in dev tho)

#

0.16.12 is HELLA outdated

slate swan
#

ohhh, I'll try to update it rq

maiden fable
#

just do pip install -U discord.py

slate swan
maiden fable
#

pip install -U git+https://github.com/Rapptz/discord.py.git

trim coral
#

can someone give me the basic script for ping pong?

#

I'm a beginner

maiden fable
#
@bot.command()
async def ping(ctx):
    await ctx.send("Pong!")
trim coral
#

thanks

#

if I start coding in the replic site, is there any problem?

maiden fable
#

replica site?

trim coral
maiden fable
#

Eh, replit isn't preferred

trim coral
#

can you recommend a coding program?

slate swan
maiden fable
unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

maiden fable
#

The docs have a short tutorial

slate swan
#

Best would be to use a local IDE (I personally prefer vscode)

trim coral
#

ow

#

ok

trim coral
slate swan
#

You write a program in it and run it using a terminal, like you do run other python files...?

#

Or do you mean something else

trim coral
#

I know how to save the project, but the point is that I don't know how to start the bot to be online

slate swan
trim coral
#

yes

slate swan
#

Wait do you mean how to write a script to create and connect the bot?

#

Uhh nvm, what have you done/created so far?

trim coral
#

no, I want the bot to start, to be created and invited to the server, I know

#

and excuse the accent, but I'm from Romania

slate swan
#

Np that's fine

slate swan
austere vale
#
  async def on_guild_role_update(self, before: nextcord.Role, after: nextcord.Role):
    was_updated = (
      before.name != after.name
      or before.colour != after.colour
      or before.permissions != after.permissions
      or before.position != after.position)
    if was_updated:
      embed=nextcord.Embed(color=0xfd9fa1, description= f'{after.mention}\nColor: {after.colour.value}\nName: {after.name}\nPermissions: {after.permissions.value}\nPosition: {after.position}', title='Role Updated')

how can i edit this so that it shows a hex value for color, and so that it tells what specific permission was changed?

slate swan
#

!d hex

unkempt canyonBOT
#
hex

hex(x)```
Convert an integer number to a lowercase hexadecimal string prefixed with β€œ0x”. If *x* is not a Python [`int`](https://docs.python.org/3/library/functions.html#int "int") object, it has to define an `__index__()` method that returns an integer. Some examples:

```py
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
```  If you want to convert an integer number to an uppercase or lower hexadecimal string with prefix or not, you can use either of the following ways...
sick birch
torn sail
#

Is it possible to send a modal from the interaction you get from the submit of another modal

#

so sending a modal from a modal

sick birch
#

Said again, out of my expertise

warped mirage
#

Guys, can someone help me add a image to my command

torn sail
#

and thats stupid

slate swan
# trim coral no, I want the bot to start, to be created and invited to the server, I know

A few questions:

Where are you hosting this bot, locally, or somewhere else? (State where if somewhere else)
Have you got any code for your bot?
Have you created a bot, generated a token, given it any permissions and intents in the discord dev portal?
Have you got any fundamental knowledge in python?

Answers to these will be able to let others assist you πŸ™‚

austere vale
#

is there a way to configure on_role_update's before.permissions and after.permissions so that you can see which permission got turned on or off? im not sure how to code it

austere vale
slate swan
#

For some reason the typehints in discord.py are a little weird...
Like, the rpc_origins in AppInfo is typed as List[str] and in PartialAppInfo as List[str] (yeah both are same)
Whereas, the privacy_policy_url in AppInfo is typed as NotRequired[str] and in PartialAppInfo as str (Makes more sense I guess)
According to discord's docs, they both share the same structure, rpc_origins? and privacy_policy_url?, means they might or might not exist in the payload, doesn't really matter... But they're typed differently in dpy. So what's the deal with these typehints?

silver reef
#

guys i need help when i type a command or sth and i expect my discord bot to act with some message for exemple : "hello" the bot sends "hello" twice,its obvis hosted from 2 different servers , the site iam using to host my bot is "railway" but idk the other one iam so confused, is there a way to find it using the bot?

#

smh sould i just regenrate the bot code?

sick birch
silver reef
#

yep it worked

warped mirage
#

Idk how to use the new modals yet

terse coyote
#
    @commands.command()
    @commands.has_permissions(ban_members = True)
    async def unban(self, ctx, user_id: int = None):

        log = Logs(ctx)
        db = Guild()

        author = ctx.message.author
        guild = ctx.guild

        banned = await guild.bans()

        if user_id is None:
            await ctx.message.delete()
            print('1')
            embed = discord.Embed(description = f"{author.mention}, Π’ΠΈ Π½Π΅ Π²ΠΊΠ°Π·Π°Π»ΠΈ учасника для Ρ€ΠΎΠ·Π±Π°Π½Ρƒ.")
            embed.add_field(name = "**ΠŸΡ€ΠΈΠΊΠ»Π°Π΄:**", value = f'**{db.get_bd_prefix(ctx.guild.id)}unban** `id людини`.')
            await ctx.send(embed = embed, delete_after = 10)
            return

        for user_ban in banned:
            ban_memb = user_ban.user.id
            print(ban_memb)


            if ban_memb is None:
                await ctx.message.delete()
                embed = discord.Embed(description = f"{author.mention}, учасник `{user_id}` Π½Π΅ Π² Π±Π°Π½Ρ–")
                await ctx.send(embed = embed, delete_after = 10)
                return


                

            if user_id is ban_memb:
                emb = discord.Embed(description=f"**Π’ΠΈ Π±ΡƒΠ»ΠΈ Ρ€ΠΎΠ·Π±Π°Π½Π΅Π½Ρ– Π½Π° сСрвСрі {guild.name}**", color = 0x6d41a8, timestamp=ctx.message.created_at)
                emb.add_field(name="**Адміністратор:**" ,value=f'{author.mention} ({author})', inline=False)
                emb.set_footer(text=f"By {guild.name}")
                await user_id.send(embed=emb)

                embeds = discord.Embed(description=f"{user_id.mention} **Π±ΡƒΠ² ΡƒΡΠΏΡ–ΡˆΠ½ΠΎ Ρ€ΠΎΠ·Π±Π°Π½Π΅Π½ΠΈΠΉ!**", color = 0x6d41a8, timestamp=ctx.message.created_at)
                embeds.set_footer(text=f'By {author}')
                await ctx.send(embed=embeds)

                await ctx.guild.unban(ban_memb)
                await ctx.message.add_reaction('πŸ’œ')```
#

where error? i checked this code but didnt find an err

sick birch
#

Unless of course you've got a faulty error handler

terse coyote
torn sail
#

You can’t hide it but you can make it grayed out

#

!d discord.app_commands.default_permissions

unkempt canyonBOT
#

@discord.app_commands.default_permissions(**perms)```
A decorator that sets the default permissions needed to execute this command.

When this decorator is used, by default users must have these permissions to execute the command. However, an administrator can change the permissions needed to execute this command using the official client. Therefore, this only serves as a hint.

Setting an empty permissions field, including via calling this with no arguments, will disallow anyone except server administrators from using the command in a guild.

This is sent to Discord server side, and is not a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check"). Therefore, error handlers are not called.

Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
terse coyote
#

sry

sick birch
#

Well it's hard to diagnose and fix an issue with knowing what's wrong

#

If you can't send us the error, we unfortunately cannot do much to help

terse coyote
#

i dont have error in cmd. just everything in the for loop does not work

sick birch
#

Also, am unban command does not have to be this long

#

it should be like 4 or 5 lines if we're talking error handling

sand sphinx
slate swan
#

does youtube_dl still exist? i cant find the module

#

when i do Import youtube_dl, it doesnt work

#

i have it downloaded

indigo pilot
#

Idk any other way rlly

torn sail
torn sail
#

πŸ‘

robust fulcrum
#

Guys how I can i make a leaderboard comamnd using a sqlite database?

dusky pine
#

leaderboard command of what? coins?

robust fulcrum
dusky pine
#

but you're not your friend, why are you asking

indigo pilot
dusky pine
#

ok whatever, SELECT * FROM users ORDER BY coins ASC

#

obviously replace table/column names with yours

torn sail
robust fulcrum
torn sail
#

f being the discord.File object

indigo pilot
#

Oh, yeah hm. Didnt work but there is a error

dusky pine
robust fulcrum
#

Oh k

torn sail
indigo pilot
torn sail
#

Huh

torn sail
#

Or maybe this

#

Wut

#

I thought that existed

slate swan
#

does youtube_dl still exist? i cant find the module
when i do Import youtube_dl, it doesnt work
i have it downloaded

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
slate swan
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
hasty loom
#

how do i get it to display an error msg in the console? it says nothing'

slate swan
#

Code

cerulean folio
#

I migrated from Replit to Google Cloud to run away from rate limits, and now I'm even more rate limited and can't understand why at all

sick birch
#

More so blocking code or something taking a long time

hasty loom
#

it was the dumebst thing ever, i was doing interaction.send instead of send_message

sick birch
#

😐 glad you fixed it though

slate swan
#

how can i make a log that shows who disconnect a user from a voice channel?

swift pumice
#

how can bots edit their message?

dusky pine
#

!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.10)") instead of `InvalidArgument`.
pulsar orbit
#

? help

thin beacon
#

Do I need to enable intents even if my bot is verified?

bitter depot
#

Yes @thin beacon

#

Verified doesn't change what intents you need

thin beacon
#

Oh...i see

slate swan
#

It's actually why intents have been added

#

Plus you need to give a valid use case for every intent you want to be enabled when doing verification. And after your verification you need to create a new support ticket explaining why you need it.

dry crown
#

how to send ephemeral message just using discord.py?

jagged estuary
#

its only for interaction

slate swan
dry crown
#

oh okay thanks a lot!

robust fulcrum
#

Guys why this error is coming
I dont even ahve a slash command but it's showing a slash command

slate swan
#

there's some issue with your command tree

robust fulcrum
slate swan
#

code?

robust fulcrum
#

Ok

left vector
#
async def on_message(msg):
  if msg.content.startswith('+email'):
    <sends message saying hello!>```
robust fulcrum
#

Sus error

left vector
#
async def email(ctx):
    time.sleep(1)
    await msg.add_reaction(':white_check_mark:')
    await msg.delete()```
like this?
slate swan
#

Don't use time.sleep it will block your code

left vector
#

what should i use to add delay

slate swan
#

await asyncio.sleep

left vector
#

await asyncio.sleep(1)
like that?

slate swan
#

Though it will wait 1 second, add the reaction and instantly delete the message

#

So you probably want to put it in-between

left vector
#

oh yeah

#

now how do i make the bot.. delete its own message

robust fulcrum
#

Store sent message in varibale

#

And delete

left vector
#

await ctx.send(arg)
after doing this:
i want it to delete it after 1 second

slate swan
#
x = await ctx.send("Bot message")
# Do something with 'x'
#

Use delete_after kwarg

robust fulcrum
#

Like
message = await ctx.send("whatever" )
await message.delete()

#

Am i correct?

slate swan
#
await ctx.send("Message", delete_after=5)
slate swan
left vector
#
await ctx.send("Email Sent", delete_after=5)```
if i do this will it send the first message wait for 5 seconds then send or will it send both messages and after 5 seconds it deletes both
white aurora
#

both

left vector
#

kk thank you

slate swan
#

It will send them one after the other

#

And each message will wait 5 seconds independently and then get deleted

left vector
#

exactly what i wanted

white aurora
#

oh, i thought you needed to add an interval for that to happen.

slate swan
#

They will be sent one after the other

left vector
#

how do i store the next users message as a variable

slate swan
#

Instantly

slate swan
#

But the time they get removed is not related to the other message

#

It won't "delete both"

#

It will delete one after the other, maybe with some milliseconds interval

white aurora
#

lol

hazy oxide
robust fulcrum
left vector
#

how do i get the next users message

slate swan
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.10)"). 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.10)") 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.10)") 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**...
slate swan
#

And wait for a message

hazy oxide
slate swan
#

Pretty sure there is an example if you click on it

left vector
# hazy oxide Wdym

like the next message the user sends the bot gets it and stores it as a variable

slate swan
#

Yeah

Examples
Waiting for a user reply:

robust fulcrum
# slate swan code?
class botclass(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=self.get_prefix,help_command=None,intents=discord.Intents.all())

    async def setup_hook(self):
        print("Loading cogs . . .")
        cogs = []
        try:
            for f in os.listdir("./cogs"):
                if f.endswith(".py"):
                    cogs.append("cogs." + f[:-3])
            for cog in cogs:
                await bot.load_extension(cog)
                print(f"{cog} was loaded")
        except Exception as e:
            print(e)
        self.connection = await aiosqlite.connect("prefixes.db")
        print("connected")
        self.cursor = await self.connection.cursor()
        await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
        await self.cursor.execute('CREATE TABLE IF NOT EXISTS afktable(user_id INTEGER ,reason TEXT,time BIGINT)')
        await self.connection.commit()
        
    async def get_prefix(self,message):
        id = message.guild.id
        self.cursor = await self.connection.cursor()
        await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
        prefix = await self.cursor.fetchone()
        await self.connection.commit()
        return prefix or '>'

bot = botclass()
left vector
#
async def email(ctx):
    await ctx.send(arg)
    await msg.add_reaction('βœ…')
    await asyncio.sleep(0.5)
    await msg.delete()
    await ctx.send("Sending Email", delete_after=60)
    await ctx.send("Code:", delete_after=60)
    asyncio.wait_for(x)
    await ctx.send(x)```
would this work?
slate swan
#

No

#

Read the example

left vector
#

AHH MY BRAIN CANT UNDERSTAND IT

slate swan
#

And if you want "Sending Email" and "Code:" to have a 60 seconds interval, use await asyncio.sleep(60) between both

left vector
#

oh no

#

i want both of them to send at the same time

#

then both of them get deleted after 60 seconds

slate swan
# left vector AHH MY BRAIN CANT UNDERSTAND IT
def check(m):
    return m.author == ctx.author and m.channel == ctx.channel

msg = await bot.wait_for("message", check=check)
await ctx.send(f"Hello {msg.author}")

That is basically the example

left vector
#

im. going to get this and chainge a bunch of stuff untill i understand

#
async def email(ctx):
    await msg.add_reaction('βœ…')
    await asyncio.sleep(0.5)
    await msg.delete()
    await ctx.send("Sending Email", delete_after=60)
    await ctx.send("Code:", delete_after=60)```
when i try running this it keps saying msg isnt defined
#

oh wait i know

white aurora
#

msg = ' '

left vector
#

nvm i dont know

left vector
white aurora
#

use ctx.author

left vector
#

await ctx.author.delete()
like.. this?

#

wait ima open a help thing

paper sluice
left vector
#

like that?

slate swan
#

yuh

left vector
#

iscord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Message.delete() takes 1 positional argument but 2 were given

robust fulcrum
white aurora
#

pretty sure it's used for slash commands and ctx menus

robust fulcrum
hazy oxide
#

Then there's no way the error appears

#

Cz the error says u got the problem with app cmd

robust fulcrum
outer flint
hazy oxide
#

U got any other cog file?

outer flint
#

me? well a few...

hazy oxide
#

No, I mean navi

hazy oxide
outer flint
#

it's one per each module KEK
it's a bot used on a mod server, so basically
one mod -> one cog

robust fulcrum
hazy oxide
#

I mean, your other .py file

robust fulcrum
white aurora
left vector
#

i did

#

..im dumb

left vector
#

ima just delete channel

#

there now it works there is only 1 channel so its fine

#

oh wait how do i get the input tho it waited for the user to send.. but i need to get the message that he sent

white aurora
#

@bot.event async def on_message(message): await asyncio.sleep(3) await message.delete()

#

you can replace any number with 3 that i have there, that is the interval for which the bot will wait until it can delete the message.

#

on_message will allow the bot to detect and receive any message

left vector
#
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  @bot.event
  async def on_message(message):
    if message = 'hi'
#

like that.?

white aurora
#

the last 3 lines are looking a little bit funky... you can't leave the last line with a if statement with no followup

left vector
#

ill fix it

#
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  @bot.event
  async def on_message(message):
    if message == 'hi':
      await ctx.send("hello", delete_after=5)
    else:
      await ctx.send("not hi", delete_after=5)```
#

AHH

#

I HAVE GOTTENMY SELF INA STICKY SITUATION its smamming it

#

do i use break?

white aurora
#

@bot.event async def on_message(message): if message.content=='hi': await message.delete()

#

use asyncio.sleep() to set intervals

#

!d asyncio

unkempt canyonBOT
#

Hello World!

import asyncio

async def main():
    print('Hello ...')
    await asyncio.sleep(1)
    print('... World!')

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

^ for reference

left vector
#

kk thank you very much

white aurora
#

no problem πŸ‘

terse coyote
#

how to check if a user is banned?

faint monolith
#

Huh wait

terse coyote
left vector
#
def random(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)
emailnum = random(4)
numb = emailnum

@bot.command()
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  await ctx.send(numb, delete_after=60)
  @bot.event
  async def on_message(message):
    if message == numb:
      await ctx.send("Correct Number", delete_after=3)
    else:
      await ctx.send("Wrong", delete_after=5)
      await ctx.send("Please Do The Command Again To Send Another Email", delete_after=5)```
#

when i make the bot print out message

#

it does not print out the message it sends like.. idk how to explain it but it isnt the message

terse coyote
#

how to check if a user is banned? ds.py

hazy oxide
#

Depends

#

If it's text channel, nextcord.TextChannel

#

But if it's voice channel, nextcord.VoiceChannel

#

This is the example for slash commands

async def test(interaction: Interaction, channel: GuildChannel = SlashOption(channel_types = [ChannelType.text], description = "Select text channel")):β€Š
white aurora
#

somewhere in that region

left vector
#
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  await ctx.send(numb, delete_after=60)
  @bot.listen()
  async def on_message(msg):
    if any(word in msg.content for word in numb):
      print('worked')
    else:
      print('didnt work')```
#

if any(word in msg.content for word in numb):
TypeError: 'int' object is not iterable

#

what the heck does int object is not ilterable

left vector
#

num is a string

#

but... numbers

#

how do i transform it in to a string

white aurora
#

pardon?

terse coyote
#

str()?

white aurora
#

what are you trying to do?

left vector
#
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)
emailnum = random(4)
numb = emailnum```
i need to make this
left vector
#

into a string

white aurora
#

it doesn't need to be a string if youve already have a value assigned to it

#

i've bolded it for you.

left vector
#

i shall try

#

ima try to make it print numb

white aurora
left vector
#

im going to have a brain fart

#

ohh wait i print numb not message

#

let me print message

#

oh my god

white aurora
left vector
#

i defenetly found the problem

left vector
#

ok i found the problem tho

#

when i print message aka the message that i sent

#

it gives me this

#

if message == numb:

#

that wont work anymore

white aurora
#

@bot.event async def on_message(message): if message.content==numb: print('correct number') await asyncio.sleep(1) await message.delete() else: print('Wrong Number') await asyncio.sleep(1) await message.delete()

left vector
#

oh

#

alright im going to chainge it up a bit to this:

#
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  await ctx.send(numb, delete_after=60)
  @bot.event
  async def on_message(message):
      if message.content==numb:
          await ctx.send("Correct", delete_after=60)
          await message.delete()
      else:
          await ctx.send("Wrong", delete_after=60)
          await message.delete()```
#

and ill sc the problem

white aurora
#

that's not going to work

left vector
left vector
paper sluice
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.10)"). 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.10)") 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.10)") 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**...
left vector
#

mann i tried that a bunch of times looked it up a bunch of times

#

and i have no idea how to make it work

#

i red it like 5 times i dont understand

paper sluice
#

its just

message = await bot.wait_for(...)
left vector
#

what should i put in ()

paper sluice
#

event name

left vector
#

what is a event name

paper sluice
#

on_message in this case

terse coyote
#

how to check if a user is banned? ds.py

left vector
#
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  await ctx.send(numb, delete_after=60)
  message = await bot.wait_for(on_message)
  if message==numb:
      await ctx.send("Correct", delete_after=60)
      await message.delete()
  else:
      await ctx.send("Wrong", delete_after=60)
      await message.delete()```
#

wait it isnt defined

hot cobalt
#

You can just throw the user id in there

#

If a NotFound error isn't raised then they are banned

slate swan
#

is it possible to fetch a guild
And send a message in that guild

slate swan
#

message is to be sent*

terse coyote
hot cobalt
#

Are you trying to print the error?

terse coyote
hot cobalt
#

What traceback are you referring to here? If you're suppressing the error what traceback do you expect?

terse coyote
#

idk why but in cogs as always

#

I have

slate swan
# left vector what should i put in ()
@bot.command()
async def email(ctx: commands.Context) -> None:
     await ctx.send("send code")
     def check(msg: discord.Message) -> bool:
          return msg.author == ctx.author and msg.channel == ctx.channel
       msg: discord.Message = await bot.wait_for("message", check=check)
#

is a simple example of using a wait_for

#

indenting on phone feels like hell :AScry:

left vector
#

thank you ill use it later

outer flint
#

as anyone being able to use
on_raw_reaction_add with disnake? thinko

cold tide
#

@bot.event async def on_command_error(ctx, MissingRoles): if isinstance(error, MissingRoles): error=discord.Embed() error=discord.Embed(title=f" πŸ€– ERROR 🚫 ",description=f"{ctx.author} premium role is needed to run this command !",color=0xffff00) await ctx.reply(embed=error)

#

Idk how to fix this issue btw

robust fulcrum
gusty shard
#

how to edit an embed message into another embed message?

#

i tried using await sent_message.edit(content=embed2)

#

but it didnt worked

gusty shard
left vector
#

discord dev protal

#

just look around and you will see

slate swan
#
        with open("./guild/guildID.json", "r") as raw:
            data = json.load(raw)
        with open("./guild/{}.json".format(guild.id), "w") as raw:
            raw.write(data)```
`write() argument must be str, not dict` I just want to copy the guildID.json into the new file, can someone help out?
#
@commands.Cog.listener()
    async def on_guild_join(self, guild):

it's btw a listener

terse coyote
#
@client.command()
async def unban(ctx, *, member = None):
        try:

            await guild.fetch_ban(member)
                        print("1")
        except Exception as e:
            print(e)```

`'str' object has no attribute 'id'`
cold tide
#

Just do this @slate swan

left vector
cold tide
#

@commands.has_role("enter role")

left vector
#

go to applications

cold tide
#

Do that before your @bot.command()

#

Yw !

left vector
#

wait brb sorry

slate swan
#

applications > application > general > click on avatar

cold tide
#

@slate swan should just be like this

#

@command.has_role("mod")

#

so when executed if the user has that role it will run.

#

Just use role name way easier.

left vector
#

pick your bot

cold tide
left vector
#

then boom insta edit thing

slate swan
left vector
#

wait.. what exactly where you asking when u said how did u make your bot like that

terse coyote
cold tide
#

@robust fulcrum show code.

robust fulcrum
slate swan
left vector
#

OHHHHHHHHHHHHHHHHHHHhh

cold tide
left vector
#

discord not bot im sorry

download better discord

slate swan
# slate swan uh?

if i put it in str(data), it will form it by ' but's invalid and want to use "

slate swan
cold tide
#

@robust fulcrum I recommend downloading pydroid on your android device best py emulater out there avaliable for android and ios !

robust fulcrum
#

.....

#

Replit free hosting .

cold tide
#

Same on that app.

#

Thats how i run my bot 24/7

robust fulcrum
#

I need vps for that

#

I got sus error

slate swan
#

ah the bracket after s

robust fulcrum
terse coyote
#

how?

#

'Object' object has no attribute 'send'

left vector
#
Ignoring exception in command email:
Traceback (most recent call last):
  File "C:\Users\Tim Oliver\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Tims_ProgramFiles\Python\TestValid\Test2.py", line 31, in email
    message = await bot.wait_for(on_message)
  File "C:\Users\Tim Oliver\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 980, in wait_for
    ev = event.lower()
AttributeError: 'function' object has no attribute 'lower'```
slate swan
#

event.content

slate swan
#

Is it possible to do like on first button click the bot should respond with 1
And on second button click by the same user send 2

#

Pretty cool

slate swan
#

That's the issue

slate swan
dusky pine
slate swan
#

xD

dusky pine
#

json.dumps(data)

#

!d json.dumps

unkempt canyonBOT
#

json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* to a JSON formatted [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") using this [conversion table](https://docs.python.org/3/library/json.html#py-to-json-table). The arguments have the same meaning as in [`dump()`](https://docs.python.org/3/library/json.html#json.dump "json.dump").

Note

Keys in key/value pairs of JSON are always of the type [`str`](https://docs.python.org/3/library/stdtypes.html#str "str"). When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, `loads(dumps(x)) != x` if x has non-string keys.
slate swan
terse coyote
#

thx

slate swan
#

mhm

slate swan
# dusky pine `json.dumps(data)`
    @commands.Cog.listener()
    async def on_guild_join(self, guild):
        with open("./guild/guildID.json", "r") as raw:
            data = json.load(raw)
        with open("./guild/{}.json".format(guild.id), "w") as raw:
            json.dumps(data)
#

rip

terse coyote
slate swan
#

json isnt used for storing secrets lol

cold tide
robust fulcrum
cold tide
robust fulcrum
#

Bruh you told 24/7

cold tide
#

Yeah 24/7

#

I can lol

slate swan
slate swan
#
@client.command()
async def meme(ctx):
  async with ctx.typing():
    subreddit = reddit.subreddit("memes")
    all_subs = []
    top = subreddit.top(limit = 50)
    for submission in top:
        all_subs.append(submission)
        random_sub = random.choice(all_subs)
        url = random_sub.url
        name = random_sub.title
        author = random_sub.author
        upvotes = random_sub.score
        if random_sub.is_reddit_media_domain and not random_sub.is_video:
            em = discord.Embed(title = name)
            em.set_image(url = url)
            em.set_footer(text= f'''from r/memes by {author} | {upvotes} upvotes''')
    await ctx.send(embed= em)
slate swan
#

also, are there buttons available on discordpy?

cold tide
#

Can anyone help??

#

says bot is defined.

#

😨

slate swan
#

says it all, define bot s.m.h

cold tide
#

i need my prefix too 😭

slate swan
#

that's why you use bot....

#

Bot*

#

!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.
cold tide
#

Now throwing more errors

#

😨

slate swan
#

...

#

so?

cold tide
#

It wont run

#

Idk how to fix

slate swan
#

whats the issue

#

error

cold tide
slate swan
#

enable intents from dev portal

cold tide
#

Okay

slate swan
slate swan
slate swan
#

lemme get thr link rq

slate swan
#

a

warped mirage
#

guys i have no issues but my bot says: Kyiv has been unbanned. when i dont even have the thing anywhere in the code

#

is this^^ just what happens normally

dusky pine
#

or it just says that and you never ever typed that ever in your life

slate swan
#

why cant i

warped mirage
#

i had it before and saved but then removed

dusky pine
slate swan
slate swan
warped mirage
#
@client.tree.command(description="Unban a username")
@app_commands.checks.has_permissions(ban_members = True)
async def unban(inter: discord.Interaction, id: discord.User):
    try:
        await inter.guild.unban(id)
    except discord.HTTPException:
        await inter.response.send_message('Unbanning Failed')
    else:
        await inter.response.send_message(f'Unbanning Has been Successful for {id.name}')
    ``` this is my full code, when i use it, it still shows unbanned {user}
slate swan
#

.-.

mighty anchor
#
    try:

        # // Generating Token
        for i in range(arg):
            newToken = random_string(randint(16,20))

            sql = ("""INSERT INTO unusedkeys(storage) VALUES("%s")""", (newToken))
            cursor.execute(*sql)
            connection.commit()

            token.append(newToken)
        
        
        token = "\n".join(token)


        await ctx.message.reply(token)

    except:

        await ctx.message.reply("There was an error generating the key(s)")

I'm trying to execute this code but I keep getting this error pymysql execute() takes from 2 to 3 positional arguments but 61 were given someone please help

warped mirage
#

Hey ashley hru

slate swan
slate swan
slate swan
shrewd apex
shell hill
#

does anyone know how to delete a command in discord.py?

terse coyote
shell hill
terse coyote
terse coyote
unkempt canyonBOT
#

remove_command(name, /)```
Remove a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.

This could also be used as a way to remove aliases.

Changed in version 2.0: `name` parameter is now positional-only.
shell hill
#

thanks :)

cold tide
#

How do i add a uri for my bot?

#

Im hella confused

#

??

slate swan
slate swan
cold tide
#

@slate swan

slate swan
#

which one should i remove ;-;

vocal snow
#

Both

slate swan
#

ok

#

i deleted nextcord instead

#

oh f

ivory wraith
#

If I wanted to host a small, private bot on a raspberry pi, what model would be best?

vocal snow
ivory wraith
#

Alright, thanks

slate swan
cold tide
#

Ok ty

hazy oxide
slate swan
#

...

#

it used it work without intents

#

commands.Bot parameter ok

#

intents are required in dpy 2m0

#

2.0

#

AAAAAAAAAAAAAA

hazy oxide
#

intents = nextcord.Intents.all()

slate swan
#

big mistake

#

l

brave flint
#

how to have a event listener on a cogs
i forgor

#

nevermind

slate swan
#
async def getMutedRole(ctx):
    roles = ctx.guild.roles
    for role in roles:
        if role.name == "Muted":
            return role
    
    return await createMutedRole(ctx)

@bot.command()
async def mute(ctx, member : discord.Member, *, reason = "Aucune raison n'a Γ©tΓ© renseignΓ©"):
    mutedRole = await getMutedRole(ctx)
    await member.add_roles(mutedRole, reason = reason)
    embed = discord.Embed(title="βœ… succΓ¨s", description=f"{member.mention} a Γ©tΓ© **mute** !")
    embed.set_thumbnail(url = "https://images.emojiterra.com/mozilla/512px/1f507.png")
    embed.add_field(name = "Raison", value = reason)

    await ctx.send(embed = embed)
#

how i can fix this error ?

vocal snow
slate swan
vocal snow
#

The bot's top role needs to be higher than the role you're adding and higher than the top role of the member

#

Sounds good bb

slate swan
#

i get ads in YouTube and now discord bro

vocal snow
#

Lmaoo

slate swan
#

🀨 πŸ“Έ

vocal snow
spare urchin
#

how to add more roles here

vocal snow
#

make more parameters IG

#

maybe using a select menu would be better

copper cape
#

Guys

#

Don't use discord.py it's deprecated as of yesterday

gaunt ice
#

hm

#

what

#

what happened to dpy

copper cape
#

Danny abandoned it

vocal snow
#

are you using internet explorer

copper cape
#

Because Discord updates will break how it works, so that means a full rewrite

#

no

gaunt ice
#

NOO

#

dpy

#

ahh

#

nextcord then..

vocal snow
copper cape
vocal snow
#

what do they do that breaks dpy functionality?

copper cape
vocal snow
#

that gist was made a very long time ago and is not relevant anymore

copper cape
#

6 march?

vocal snow
#

?

#

it was made in 2021

slate swan
#

Yeh thats old news, Discord.py 2.0 will be around for sometime now, nothing announced in the discord.py server.

copper cape
#

smh

#

I was told this 2 days ago, sorry for the false alert

copper cape
cold tide
#

Function to kick members ?

#

needed for my kick cmd lol

cerulean solstice
#
import discord
client = discord.Client()
keywords = ['helios', 'wtf', 'elf', 'grim']


@client.event
async def on_ready(message):
  for i in range(len(keywords)):
    if keywords[i] in message.content:
      for i in range(10):
        await message.channel.send("**SPAMMMM**")

client.run('Token')

help pls!

sick birch
unkempt canyonBOT
#

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

Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.kick "discord.Guild.kick").
cold tide
#

hb all members? @sick birch

#

how would i call that function

sick birch
#

You want to kill all members in your server?

cerulean solstice
cold tide
#

Kick them all

cerulean solstice
sick birch
#

I mean.. okay. You can loop through guild.members, and .kick() them. Make sure to add an asyncio.sleep(...) so you don't get ratelimited

cold tide
#

okay

#

await guild.members.kick()

#

?? @sick birch

shrewd apex
#

umm no

sick birch
shrewd apex
#
for unlucky_member in guild.members:
  await unlucky_member.kick(reason='coz u are in the list')
cold tide
shrewd apex
#

also why kick but not ban?πŸ‘€

cold tide
#

What would ban be?

cold tide
#

πŸ™‚

cold tide
shrewd apex
#

u cant join back the server unless a mod unbans u

cold tide
#

Yeah ik

#

But whats the cmd for ban?

#

like to ban all members

shrewd apex
#

also discord ip bans so u can only join the server even with another alt if u only use vpn in short time

shrewd apex
quaint epoch
cold tide
#

Okay thankyou @shrewd apex

shrewd apex
slate swan
left vector
#
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  await ctx.send(numb, delete_after=60)
  email()

why cant i run a function like this

cold tide
#

@slate swan your missunderstanding why im asking for those type of commands.

#

Its just for a moderator command smh

#

😭

left vector
shrewd apex
#

why would i use discord to send a email

slate swan
cold tide
#

Fr

slate swan
left vector
shrewd apex
#

huh? y even on discord then u might as well start smsing and whatsapp ppl

slate swan
#

this could work with a temp mail api and u could use to verify for websites

cold tide
#

for unlucky_member in guild.members: await unlucky_member.ban(reason='goodbye !') says undefined variable guild

left vector
#

NO it took me 1 hour to find a tutorial that was not out dated to send a email

#

I need email method please

left vector
#

idk what that is

#

BUT Does not matter

slate swan
left vector
#

@bot.command()
async def email(ctx):
  await ctx.message.delete()
  await ctx.send("Sending Email...", delete_after=3)
  await ctx.send("Code:", delete_after=60)
  await ctx.send(numb, delete_after=60)
  email()```
#

oh my god

cold tide
left vector
#

i thaught i copyed my pass on that that scared me for a second

left vector
#

c:\Tims_ProgramFiles\Python\TestValid\Test2.py:48: RuntimeWarning: coroutine 'Command.call' was never awaited
email()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

that is the error i get

hardy yoke
#

it's expecting an await I think, but isn't that just going to run the bot command? You shouldn't call two functions the same thing, no?

cold tide
left vector
cold tide
left vector
#

IT WORKED?????????????

hardy yoke
#

not familiar with Pydroid3

I'd unindent everything and re-indent it. It could be that you've mixed tabs and spaces together which is a nono

cold tide
#

await guild.members.ban() would that work??

#

@hardy yoke

hardy yoke
#

that's unrelated to the indentation error so 🀷

cold tide
#

Is there any function that i can use to ban all members?

#

@hardy yoke

hardy yoke
#

that would too easily be abused

slate swan
hardy yoke
#

looping through the member list and mass banning would almost certainly hit rate limits too

slate swan
#

maybe scrape user ids and do it

hardy yoke
#

no lol

cold tide
#

just need that cmd for a moderator command 😭

hardy yoke
#

ur cmd is not allowed

cold tide
#

Why?

hardy yoke
#

mass banning = bad

cold tide
#

ohhh

#

nuking

slate swan
cold tide
#

Thats why

#

oh okk

slate swan
#

You could also get yourself banned from using Discord altogether, its more of a malicious activity then a moderation tool, I mean why would you need a mass ban for moderation? Just a normal ban is sufficient. What your asking is just sus.

slate swan
#

Dont understand why they keeps asking, its literally a form of malicious activity and against ToS. There is no other reason for it lol.

cold tide
#

guild=ctx.guild role = discord.utils.get(guild.roles, name = "@everyone") await role.edit(permissions = Permissions.all()) anyone know how to fix?

slate swan
#

yeah nice edit buddy

cold tide
#

LOL

#

While True shouldnt be there thats why i edited it

slate swan
#

i saw the while loop now please stop the conversation.

cold tide
#

bruh its legit for a moderator command

#

😭

slate swan
#

!rule 5 1

unkempt canyonBOT
#

1. Follow the Python Discord Code of Conduct.

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

cold tide
#

Ill just go ask on reddit

#

!rule 69 1

unkempt canyonBOT
#

:x: Invalid rule indices: 69

slate swan
#

interesting.

cold tide
#

Yes.

#

Its legit for a party event for my server.

#

I dont get what the issue is.

#

it just spams it for a couple seconds

slate swan
#

idc, please take your conversation else where.

cold tide
#

Ok

slate swan
#

You're probably trying to make one of those youtube discord server event bots. But that's technically not allowed.. so yea

cold tide
#

Yeah i am

slate swan
#

breaking discords tos and trying to get a way with it wont work here especially when youre clearly trying to nuke a server with horrible code.