#discord-bots

1 messages · Page 315 of 1

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
slate swan
#

isnt that for ctx?

#

No, look at the part of the documentation I just linked

slate swan
cold oyster
#

In my on_raw_reaction_add can I remove the reaction of the user who added the reaction?

slate swan
#

Im having the issue that when i click a button to edit a message after 15 minutes I get the error Invalid Webhook Token u had that issue like 5 months ago

cold oyster
naive briar
#

!d discord.Message.remove_reaction 🫠

unkempt canyonBOT
#

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

Remove a reaction by the member from the message.

The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).

If the reaction is not your own (i.e. `member` parameter is not you) then [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) is needed.

The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake) abc.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
cold oyster
slate swan
#

its about the error 401 Unauthorized (error code: 50027): Invalid Webhook Token

#

I know a lot of ppl ran into this error but I never seen anyone found a fix to it

#

Apparently it was a Discord Issue like 2 years ago

#

-_-

#

don't interaction responses freeze after 15 minutes or something like that

#

or am I just thinking of the ephemeral ones disappearing

naive briar
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
naive briar
#

Okay then

slate swan
naive briar
#

Oh it just loaded

#

I'd suggest you to respond with interaction.response.edit_message directly instead of deferring the interaction and editing the stored message

naive briar
golden portal
#

instead of doing interaction.response.defer + view.message.edit in ArticlePaginationView, you should directly use interaction.response.edit_message inside update_message

#

can't really elaborate more than that

golden portal
#

what was the code that you tried?

whole hamlet
#
    @commands.Cog.listener()
    async def on_guild_channel_create(self, channel):

        async with self.bot.db.execute("SELECT threshold FROM ban WHERE guild_id = ?",(channel.guild.id)) as cur: check = await cur.fetchone()

        async for i in channel.guild.audit_logs(limit=None, after=datetime.now() - timedelta(seconds=5), action=discord.AuditLogAction.channel_create):
          
          await self.bot.db.execute('''INSERT INTO banaudit (guild_id, users) VALUES (?, ?)''', (channel.guild.id, i.user.id))
          await self.bot.db.commit()

          counter = 0
          async with self.bot.db.execute("SELECT * FROM banaudit WHERE guild_id = ? AND users = ?", (channel.guild.id, i.user.id)) as cur: data = await cur.fetchone()
          if data:
              counter += 1
        
          if counter == check:
              await channel.guild.kick(i.user)

I'm trying to make limits for my antinuke. so if a user makes more channels than what the threshold is it'll kick them but no error

naive briar
#

Ok

lyric tinsel
#

what I can tell though is counter is one variable for every single audit log channel create entry?

#

and how is creating many channels a nuke

kind roost
#

????

slate swan
naive briar
#

Or is that discord.py at all pithink

shrewd fjord
#

!d discord.ui.RoleSelect

unkempt canyonBOT
#

class discord.ui.RoleSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current roles of the guild.

Please note that if you use this in a private message with a user, no roles will be displayed to the user.

New in version 2.1.
shrewd fjord
#

hm

spark nimbus
#

do some one knows whats that error?

    await interaction.response.edit_message(content="Allows server moderators kick pople from the server", ephemeral = False)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: InteractionResponse.edit_message() got an unexpected keyword argument 'ephemeral'

the code:

class Select(discord.ui.Select):
    def __init__(self):
        options=[
            discord.SelectOption(label="kick",emoji="🦵🏻",description="this kick people from the server"),
            discord.SelectOption(label="ban",emoji="✨",description="this ban people from the server"),
            discord.SelectOption(label="clear",emoji="🧹",description="this clears messages")
            ]
        super().__init__(placeholder="Select an option",max_values=1,min_values=1,options=options)
    async def callback(self, interaction: discord.Interaction):
        if self.values[0] == "kick":
            await interaction.response.edit_message(content="Allows server moderators kick pople from the server", ephemeral = False)
        elif self.values[0] == "ban":
            await interaction.response.send_message(content = "Allows server moderators ban pople from the server",ephemeral=False)
        elif self.values[0] == "clear":
            await interaction.response.send_message(content = "Clear messages in chat",ephemeral=False)

class SelectView(discord.ui.View):
    def __init__(self, *, timeout = 180):
        super().__init__(timeout=timeout)
        self.add_item(Select())

@client.hybrid_command()
async def help_administration(ctx):
    await ctx.send("Help administration command menu!",view=SelectView())```
#

await interaction.response.edit_message(content="Allows server moderators kick pople from the server", ephemeral = False)

#

line 40^^^^

golden portal
#

you pretty much can't edit a message into ephemeral

spark nimbus
#

ohhh

#

my bad

golden portal
#

new times roman killin it

still spade
#

whats the api for purge cmd

cloud dawn
#

!d discord.TextChannel.purge

unkempt canyonBOT
#

await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.

You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.

Changed in version 2.0: The `reason` keyword-only parameter was added.

Examples

Deleting bot’s messages...
still spade
#

ty

sick coyote
#

when im selecting my select menu, it doesnt reset the choice it will stay applied, how can i reset the choices?

whole shoal
#

I mean I found a way around it

#

Instead of editing the webhook, I just sent the message in same channel

left dew
#

hello, i’ve got a code that contains two tasks.loop, however if multiple users start the loops at the same time then i get an error. is there any way i can avoid this and allow multiple people to start multiple loops whenever?

shrewd fjord
shrewd fjord
slate swan
#

,paste

#

?paste

#

!paste

left dew
naive briar
unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

left dew
#

and i want to know how i would be able to

naive briar
#

You're not supposed to do that

#

Not with discord.ext.tasks.Loop, but maybe with asyncio.Task

left dew
#

with asyncio.task i can start two of the same loops at the same time?

naive briar
#

Whoops

#

!e sure

import asyncio

async def work(wid: int):
    print(f"[{wid}] started")
    await asyncio.sleep(0.5)
    print(f"[{wid}] stopped")

async def main():
    loop = asyncio.get_running_loop()

    loop.create_task(work(1))
    loop.create_task(work(2))

    await asyncio.sleep(0.6)

asyncio.run(main())
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | [1] started
002 | [2] started
003 | [1] stopped
004 | [2] stopped
left dew
#

oh sweet

#

so that’s solved my issue then

naive briar
#

Sometimes I forget how asyncio work

left dew
#

lol

left dew
lost cradle
#

I want to locally host my bot, can I run it without my IDE? don't want to edit, just have the bot running. its fairly lightweight

#

Don't want to have it always on either

#

just when Im on my pc i can have it running

brazen raft
# naive briar !e sure ```py import asyncio async def work(wid: int): print(f"[{wid}] star...

What's wrong with using asyncio.create_task instead of retrieving an event loop object to do so? Or better yet, using an asyncio.TaskGroup:

from asyncio import run, sleep, TaskGroup

async def work(wid int):
    print(f"[{wid}] started")
    await sleep(0.5)
    print(f"[{wid}] stopped")

async def main():
    async with TaskGroup() as tg:
        tg.create_task(work(1))
        tg.create_task(work(2))

run(main())

A task group waits for its tasks to finish without you having to worry about it

#

(if you're using it as a context manager)

brazen raft
unkempt canyonBOT
#

Hello World!

import asyncio

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

asyncio.run(main())
```...
brazen raft
left dew
brazen raft
lost cradle
#

just run it with no interface so that it takes minimal resources

brazen raft
left dew
brazen raft
left dew
brazen raft
left dew
brazen raft
#

Is it decorated with @tasks.loop() or is it just an undecorated asynchronous function?

left dew
brazen raft
#

What does it do? What is it for? Why does it need to run in a loop?

lost cradle
left dew
brazen raft
#

What are channel_id and message_id for?

left dew
naive briar
brazen raft
naive briar
brazen raft
#

You should be using the high level API for normal stuff

brazen raft
#

If it opens a terminal window and immediately closes, it means an unhandled exception was raised

lost cradle
brazen raft
left dew
naive briar
brazen raft
lost cradle
brazen raft
unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
brazen raft
#

You can decorate incoming with @tasks.loop() (there's probably an example in the link)

left dew
#

i dont want to use that though because i want to start the same task more than once

brazen raft
#

This sort of loop calls incoming every set period of time

left dew
#

but i want to start the loop multiple times for different users and with tasks.loop i get an error when more than 1 of the same loop is started

lost cradle
#

what should I open the .py file with?

brazen raft
# left dew but i want to start the loop multiple times for different users and with tasks.l...

Oh, you should just have an infinite while True: loop with calls to asyncio.sleep like this:

async def incoming(channel_id, message_id):
    ...

async def button_interaction_handler(...):
    while True:
        await incoming(interaction.channel.id, msg.id)
        await asyncio.sleep(delay)

Forgive me for not having learned discord.py components yet, but this should do if you define delay somehow. It's the delay in seconds between each time incoming will be called with that interaction's channel ID and whatever msg.id is

left dew
#

okay thanks

brazen raft
#

The call to asyncio.sleep is important as this is what lets other stuff do work after letting incoming do its thing every iteration

left dew
#

ill probbaly have py while True: await incoming(interaction.channel.id, msg.id) await asyncio.sleep(delay)
at the bottom of the button class because its the last thing to do after the button has been clicked

brazen raft
#

Is it critical to continue calling incoming with the same arguments after the bot shuts down due to internet problems or simply after a shutdown?

#

The interaction might be invalid anyway in that case but I'm not entirely sure. I'm new to this interaction system in discord.py

brazen raft
left dew
#

when the transaction has been detected ill make it stop the loop

lost cradle
brazen raft
# naive briar And why is that?

From the official docs:

asyncio provides a set of high-level APIs to:

  • run Python coroutines concurrently and have full control over their execution;
  • perform network IO and IPC;
  • control subprocesses;
  • distribute tasks via queues;
  • synchronize concurrent code;

Additionally, there are low-level APIs for library and framework developers to:

  • create and manage event loops, which provide asynchronous APIs for networking, running subprocesses, handling OS signals, etc;
  • implement efficient protocols using transports;
  • bridge callback-based libraries and code with async/await syntax.
#

You only need to mess with the low level API for OS signal handling, as specified in the docs I guess

naive briar
#

I suppose, if you only need to create tasks and not nothing else that would require you to have a loop yourself

naive briar
brazen raft
#

You're certainly advised to mess with the low level API to set an event loop policy of your own, that I know

brazen raft
#

asyncio in general manages event loops under the hood

brazen raft
naive briar
#

Maybe ask me when I actually want to

brazen raft
#

concurrent.futures.ProcessPoolExecutor literally manages process pools for you

naive briar
#

That's what I'd use as the executor for the run_in_executor 🤷

brazen raft
#

I don't know how nicely multiprocessing plays with asynchronous functions

#

Kind of sounds like a bad idea to let Python schedule OS processes

naive briar
#

I've never reach the point when I actually need parallelizm, to be honest 😔

brazen raft
#

Number crunching on large data

#

That's off-topic for this channel but meh

brazen raft
#

If you want to reassociate .py files with it, maybe run the installer again and choose the repair option, idk

#

Opening a terminal and running programs from it is a good idea anyway when you might not have set up logging

brazen raft
# lost cradle what should I open the .py file with?

Normally, after installing Python using a Windows installer from python.org, all .py files are associated with the py launcher for Windows if you happened to select that option in the installation process, but PyCharm may override that when it is installed after installing Python like this

white citrus
#

Question for persitant view

Does it save all buttons from all servers that were created with this view?

hushed galleon
final iron
#

What’s the rate limit on banning members?

slate swan
#

For? Libraries handle that

final iron
#

Banning guild members

slate swan
#

For what purpose do you need it

#

Libraries already handle rate limits

final iron
#

I know, I’d like to keep the actual rate limit in mind though

slate swan
#

There's no fix rate limits given for endpoints

#

There's the global rate limit of 50/sec and the rest is per endpoint and the library reading the headers as rate limits can change and are not fixed

final iron
#

Doesn’t discord have rate limits on specific endpoints?

slate swan
#

They do

#

And they communicate that rate via the headers, as mentioned, as they are dynamic and not fixed, as also said

#

You won't get a list of all endpoints and their relative rate limits

final iron
#

What error is thrown when you’re ratelimited?

brazen raft
#

An HTTP response with the code 429 (Too Many Requests)

slate swan
#

!d discord.RateLimited

unkempt canyonBOT
#

exception discord.RateLimited(retry_after)```
Exception that’s raised for when status code 429 occurs and the timeout is greater than the configured maximum using the `max_ratelimit_timeout` parameter in [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client).

This is not raised during global ratelimits.

Since sometimes requests are halted pre-emptively before they’re even made, this **does not** subclass [`HTTPException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.HTTPException).

New in version 2.0.
brazen raft
#

I didn't know there's an exception in discord.py for this

slate swan
#

And for the raw HTTP response, it's in the link I've sent

brazen raft
# unkempt canyon

Is it raised when a method like discord.Member.ban is being rate limited?

#

I thought these methods normally call asyncio.sleep under the hood until the rate limit is up (before actually sending a request which will rate limit)

hushed galleon
young dagger
#

Still not possible to ban users with unusual DM activty?

#

I want to create a task that check for suspicious users and ban them from the server

slate swan
#

As you show in the screenshot, looks like not

brazen raft
slate swan
#

That's the amount of requests remaining

final iron
#

What permissions are required for changing a server vanity invite link?

slate swan
#

If you hit that before it has been reset, you'll hit the rate limit of the endpoint

brazen raft
slate swan
#

And before that, there's the 50/sec global rate limit you'll hit

slate swan
brazen raft
#

Hold on, why is the rate limit response received with 204? That's No Content, not Too Many Requests

slate swan
#

Because as the documentation says

#

you'll get these headers all the time, for every request

#

So that libraries can keep track of that and not even hit the 429 rate limit

#

Libraries should not make a request if it knows it will hit 429

brazen raft
#

Is it standard to send rate limit data per response to an endpoint?

#

Anyway that's off-topic

white citrus
slate swan
#

Each API on the internet does it differently

#

Some have fixed rate limits that you don't need headers

#

Some are like Discord and dynamic, so sending headers is indeed useful

brazen raft
#

I thought pre-rate-limit notifications were standardized

#

But I guess Discord is doing its own thing with buckets or something

slate swan
#

It's not something new, special or unique to Discord

#

It's used quite a lot

brazen raft
#

It is useful but I thought it would've been standardized

hushed galleon
# white citrus And how can i save them forever

if your views are stateless (for example they don't have any parameters in __init__ that change between various messages), you can construct the view and add it to your bot once without using the add_view(message_id=) parameter, and that one view instance will start responding to any message you've sent before with the same custom_id, which is pretty convenient

if your views do need state like a user object (perhaps they own the view and you only allow that person to use the buttons), you will have to store that information along with the message ID onto disk, preferably a database, and then load the objects back during bot startup

young dagger
slate swan
#

Because it's Discord

white citrus
#

My buttons have all stored in a db with message id and custom id

slate swan
#
@bot.command(name="shorten")
async def shorten(self, ctx, url):
    shorturl = requests.get(f"is.gd/create.php?format=simple&url={quote(url)}").text
    await ctx.send(f"Your link ({url}) has been shortened to: {shorturl}")
#

my code

#

my error - Traceback (most recent call last): File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1349, in invoke await ctx.command.invoke(ctx) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1015, in invoke await self.prepare(ctx) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 932, in prepare await self._parse_arguments(ctx) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 839, in _parse_arguments transformed = await self.transform(ctx, param, attachments) File "/home/runner/Reaper/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 691, in transform raise MissingRequiredArgument(param) discord.ext.commands.errors.MissingRequiredArgument: url is a required argument that is missing

devout drum
#

anyone know how i can get my bot to send a message after a command is used like discord does when ur in call for too long and it kicks you out

final iron
slate swan
#

ye

#

fixed it already

hushed galleon
final iron
#

If I connect another instance of my bot to discords API, would the original instance keep running as normal?

hushed galleon
#

i would assume it's fine given that its somewhat common for beginners to accidentally run two instances at the same time and get two responses from a single command, but im not sure if the documentation has any explicit guarantees about running two processes on the same "shard"

#

well, actual sharding has this statement:
https://discord.com/developers/docs/topics/gateway#sharding

... sessions do not have to be identified in an evenly-distributed manner when sharding. You can establish multiple sessions with the same [shard_id, num_shards], or sessions with different num_shards values. This allows you to create sessions that will handle more or less traffic for more fine-tuned load balancing, or to orchestrate "zero-downtime" scaling/updating by handing off traffic to a new deployment of sessions with a higher or lower num_shards count that are prepared in parallel.

pliant jay
#

how do i set a mobile status to a bot

final iron
#

discord.py doesn't support it, so you'll either need to find a library that does, or edit the source yourself

#

Changing a libraries source code can be incredibly unstable, so it's not recommended

whole hamlet
#
    @commands.Cog.listener()
    async def on_guild_channel_create(self, channel):

        async with self.bot.db.execute("SELECT threshold FROM ban WHERE guild_id = ?",(channel.guild.id)) as cur: check = await cur.fetchone()
        print(f'check = {check}')

        async for i in channel.guild.audit_logs(limit=None, after=datetime.now() - timedelta(seconds=5), action=discord.AuditLogAction.channel_create):
          
          await self.bot.db.execute("INSERT INTO banaudit VALUES (?,?)", (channel.guild.id, i.user.id))
          await self.bot.db.commit()

          print('test')

          counter = 0
          async with self.bot.db.execute("SELECT * FROM banaudit WHERE guild_id = ? AND users = ?", (channel.guild.id, i.user.id)) as cur: data = await cur.fetchone()
          print(f'test2')
          if data:
              counter += 1
          print('test3')
          if counter == check[0]:
              print('test4')
              await channel.guild.kick(i.user)

kicks the user when the threshold is 1 in the database but not when it’s set to any other number, any help? I’m trying to make limits

hushed galleon
timid fable
#

I am trying to create a HTTP-Only/Interactions-only bot
I got told to use stuff like Aiohttp, Quart, Flask, Fastapi, etc.
but idk where to start, any help?
All i am currently expecting is my bot to be online (with no status icon to make sure its HTTP or Interactions only)

slow ether
slate swan
#

I still dont understand how to fix:

discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token```
turbid condor
slate swan
#

thats whats causing the error

#

is what I think as of now,

turbid condor
#

Doesn't look like it

#

Can you send the whole snippet

#

Cuz according to the error it looks an issue with your webhook's link

slate swan
turbid condor
#

Then its a followup ig

slate swan
#

and if I dont use

await interaction.response.defer()```

it says:
```py
Not Found (error code: 10015): Unknown Webhook```
turbid condor
#

Yeah need to look at code

slate swan
#

If choosing a deferred response, the user will see a loading state for the interaction, and you'll have up to 15 minutes to edit the original deferred response using Edit Original Interaction Response.

#

And this is whats happening to me

turbid condor
#

The fuck

turbid condor
#

After the defer

slate swan
turbid condor
#

I don't have access to the channel

#

For me its unknown

slate swan
#

reload discord

#

that should fix it

turbid condor
#

Nope it won't

#

It's cuz of the forum being locked

slate swan
turbid condor
#

Or the channel

slate swan
turbid condor
#

404

slate swan
#

im gonna DM u a new link

#

one sec

#

@turbid condor dms

verbal drift
#

does anyone know where i can be provided a proxy server in both http and https for free? it's for a scrape bot linked to discord.

turbid condor
verbal drift
#

and i can't afford a proxy server

#

atm

slate swan
turbid condor
#

Welp you might need to look on a search engine

verbal drift
slate swan
#

or just click on my profile and click dm

verbal drift
#

anyways where can i get one for free?

frail notch
#

Hi, what lib should I use for slash commands?

frail notch
#

alr

#

thanks

fiery cairn
#

Hi there, I'm pretty new to python
How do I fix this command to work?

@bot.tree.command(name="dm", description="DM's a user of choice")
@app_commands.describe(user="Member to message", message="Message to send")
async def dm(interaction: discord.Interaction, user, message):
    await user.send(f"{interaction.user.name} has sent you a message. \n{message}")
    await interaction.response.send_message(f"Message sent successfully to {user}")
#

How do I set parameters?

slate swan
#

annotate them to corresponding types

fiery cairn
#

Thank you

fiery cairn
# slate swan annotate them to corresponding types

Ok so like

@bot.tree.command(name="dm", description="DM's a user of choice")
@app_commands.describe(user="Member to message", message="Message to send")
async def dm(interaction: discord.Interaction, user, message:str):
    await user.send(f"{interaction.user.name} has sent you a message. \n{message}")
    await interaction.response.send_message(f"Message sent successfully to {user}")
#

But how would I set user to make it so that they have to select someone in the guild

slate swan
#

i was more like talking about the user

slate swan
fiery cairn
#

oh ok

#

oh ok

#
@bot.tree.command(name="dm", description="DM's a user of choice")
@app_commands.describe(user="Member to message", message="Message to send")
async def dm(interaction: discord.Interaction, user:discord.Member, message):
    await user.send(f"{interaction.user.name} has sent you a message. \n{message}")
    await interaction.response.send_message(f"Message sent successfully to {user}")```
slate swan
#

👍

fiery cairn
#

Thanks

slate swan
#

but im not making it alone

#

yo down question

quick gust
#

i see

slate swan
quick gust
#

yep got it

slate swan
#

right asking help in here to make a python script that can banned player in a game agents the roles in here or no

#

just making sure before doing anything that can get me banned

quick gust
#

that question is very confusing

slate swan
#

i mean are we allowed to ask for help to make a script that can like mod a game or hack

#

just wondering bc i made a script for a game called rec room that can banned player just my there username

#

just wondering

upbeat otter
#

Hello

stark nexus
#
class music_tool(discord.ui.View):   
    def __init__(self):
        super().__init__()
        self.value = None

    @discord.ui.button(label="Pause", style=discord.ButtonStyle.grey)
    async def pause(self, button: discord.ui.Button, interaction: discord.Interaction):
        voice = discord.utils.get(client.voice_clients, guild=interaction.user.guild.id)
        if voice.is_playing():
            voice.pause()
            await interaction.response.send_message("Music paused!")
        else:
            await interaction.response.send_message("There no music playing right now!")```
how can i solve this?
mystic marsh
stark nexus
mystic marsh
stark nexus
mystic marsh
#

also if queues[id] != []: this can just be
if queues[id]

stark nexus
shrewd apex
#

shouldn't really compare lists like that

stark nexus
#
@client.tree.command(description="Listen to Splatune 1/2/3")
async def play_splatune(interaction: discord.Interaction, ver: app_commands.Choice[int], music: str):
        url = "https://cdn.wikimg.net/en/splatoonwiki/images/"

        if (ver.value == 0):
            tune = "Splatune”
            game = "Splatoon1"
            album = url + "2/26/Splatune.jpg"
        elif (ver.value == 1):
            tune = "Splatune2"
            game = "Splatoon2"
            album = url + "8/88/Splatune2.jpg"
        elif (ver.value == 2):
            tune = "Octotune"
            game = "Splatoon2(octo expansion)"
            album = url + "2/27/Octotune_album_cover_famitsu.jpg"
        elif (ver.value == 3):
            tune = "Splatune3"
            game = 
"Splatoon3"
            album = url + "6/65/Splatune_3_Cover.jpg"

        voice = interaction.user.guild.voice_client
        music_name = (f"{game}/music/musics/{music}.mp3")
        sourse = FFmpegPCMAudio(music_name)
        player = voice.play(sourse, after=lambda x=None: check_queue(interaction.user.guild.id))

        embed = discord.Embed(title=f"Playing {tune}", description=f"Currenly playing {music} !\n[Check Inkdepia for the correct music name!](https://splatoonwiki.org/wiki/Splatune)")
        embed.set_thumbnail(url=album)
        await interaction.response.send_message(embed=embed)```
stark nexus
shrewd apex
unkempt canyonBOT
#
Traceback

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

A full traceback could look like:

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

If the traceback is long, use our pastebin.

shrewd apex
#

talking about the previous code snippet

stark nexus
shrewd apex
#

thats not the whole thing

#

it doesn't even say the error name

stark nexus
#

@shrewd apex (sry for ping)

shrewd apex
#

show the check queue function

stark nexus
shrewd apex
#

aight do it like this

lambda _: check_queue(interaction, interaction.user.guild.id)
#

u need to pass the interaction as well

shrewd apex
#

u have a command named queue

shrewd apex
stark nexus
stark nexus
shrewd apex
#

!e None.is_playing()

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     None.is_playing()
004 |     ^^^^^^^^^^^^^^^
005 | AttributeError: 'NoneType' object has no attribute 'is_playing'
shrewd apex
stark nexus
stark nexus
stark nexus
shrewd apex
#

voice is None lmao u need to make sure its not

stark nexus
shrewd apex
shrewd apex
shrewd fjord
#

wo

stark nexus
shrewd fjord
#

!d discord.Client.voice_clients

unkempt canyonBOT
#

property voice_clients```
Represents a list of voice connections.

These are usually [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient) instances.
shrewd fjord
#

hm

#

asher

shrewd apex
#

if voice and voice.is_playing()

#

yes

shrewd fjord
#

voice = discord.utils.get(client.voice_clients, guild=interaction.guild)
@stark nexus VoiceClient.guild is a discord.Guild obj but you were passing the guild's id not the guild itself

shrewd fjord
shrewd fjord
#

yh

#

!d discord.utils.get

unkempt canyonBOT
#

discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).

When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.

To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.

If nothing is found that matches the attributes passed, then `None` is returned.

Changed in version 2.0: The `iterable` parameter is now positional-only.

Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
shrewd fjord
#

ok nvm

stark nexus
#

it worked

shrewd fjord
#

nice

stark nexus
#

ty

shrewd fjord
#

:3

stark nexus
#

if u dont mind i ask i have a error on another bot about the role

#

(drugdown menu)

shrewd apex
#

spooky gonna help he pro :p

shrewd fjord
shrewd fjord
stark nexus
#
class RoleView(discord.ui.View):
  answer1= None

  @discord.ui.select(
    placeholder="Choose a team!", 
    options=[
      discord.SelectOption(label="Smallfry", value="1"),
      discord.SelectOption(label="Pearldrone", value="2"),
    ]
  )
  async def select_role(self, interaction:discord.Interaction, select_item : discord.ui.Select):
    self.answer1 = select_item.values
    await interaction.response.defer()
    self.stop()```
shrewd fjord
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

stark nexus
shrewd fjord
#

your error showing the error in another line, maybe a command

stark nexus
#
@client.hybrid_command(description='Choose a Splatfest team!')

async def fest_team(ctx):
  view = RoleView()

  await ctx.send(view=view)

  await view.wait()

  results = {

      "a1": view.answer1

  }

  if results == "'a1': ['1']":
      team = "Smallfry"
      fest = ctx.guild.get_role(1162536798317203597)
  elif results == "'a1': ['2']":
      team = "Pearldrone"
      fest = ctx.guild.get_role(1162536915912896623)
  await ctx.send(f"You joined team " + " , enjoy your role!")
  await ctx.author.add_roles(fest)
shrewd apex
#

ayo

shrewd fjord
shrewd apex
#

what if both if and elif don't match

#

dict == string will always be false

shrewd fjord
#

he meant it select.values[0] probably

shrewd apex
#

results is a dict

shrewd fjord
#

because according to the code user cant even select two values

shrewd apex
#

his comparison is a string

shrewd fjord
stark nexus
#

if choosed team a

#

give role A

#

if choosed team b

shrewd fjord
#

i got it

stark nexus
#

give role B

shrewd fjord
#

first of all do, answer1 = select.values[0]

#

pretty sure you want the value what user wants

#

!e also

print({} == "spook")
#

forgor to add print

unkempt canyonBOT
#

@shrewd fjord :white_check_mark: Your 3.12 eval job has completed with return code 0.

False
stark nexus
shrewd fjord
#

it will be always False

stark nexus
#

oh

shrewd fjord
#

values is a listiirc

stark nexus
#

under discord.SelectOption?

shrewd fjord
#

self.answer1 = select_item.values[0]

#

!d discord.ui.Select.values

unkempt canyonBOT
shrewd fjord
#

yeah its a list

stark nexus
#

After it?

shrewd fjord
#

then you can just get rid of your result = { .. } dict

#

just directly use the view.asnwer1 in results

#

then for your if statements it will be
if results == "1":
do something
....

stark nexus
#

K

stark nexus
shrewd apex
#

queue is a command

stark nexus
#

Oh wait

#

Not that
That already solved

stark nexus
#

This one

shrewd fjord
# stark nexus

it told you to get rid of the dict ;-;
results = view.answer1

stark nexus
stark nexus
#

It worked

#

Just a question
Is it normal that the drugdown menu only can use once and second time it will have a error in "discord"? (No error in bot log)

quick gust
#

drugdown

stark nexus
shrewd fjord
stark nexus
#

Oh

stark nexus
#

Do u know where's problem?

shrewd fjord
#

and for view.wait() to work you need to stop too, so there's no problem in your code

#

its just your code that makes the select menu usable for only onetime

naive briar
# stark nexus Do u know where's problem?

If none of these if-statements are true, the fest var wouldn't exist

@client.hybrid_command(description='Choose a Splatfest team!')
async def fest_team(ctx):
...

if results == "'a1': ['1']": # <--
team = "Smallfry"
fest = ctx.guild.get_role(1162536798317203597)
elif results == "'a1': ['2']": # <--
team = "Pearldrone"
fest = ctx.guild.get_role(1162536915912896623)
await ctx.send(f"You joined team " + " , enjoy your role!")
await ctx.author.add_roles(fest)

stark nexus
#

So i should remove stop?

shrewd fjord
#

if you remove stop you need to chang your whole code strucutre

naive briar
#

Why? pithink

stark nexus
shrewd fjord
halcyon rapids
#

hi i am trying to write a discord bot that starts, does some tasks and send alerts and shuts down again. I dont really have a need fot it to listen to messages. I wrtoe this code but i cant seem to hit any error on wrong code

this is my code. Note on_ready() calls a function run_bot() which has a error statement.


async def run_bot(discord_helper, data):
    logger.info(f'Running error statement')
    1/0
    logger.info(f'Ran error statement')

@bot.event
async def on_ready():
    logger.info(f'We have logged in as {bot.user}')
    discord_helper = DiscordHelper(bot, actual_send=True)
    await run_bot(discord_helper, data)
    logger.info(f'Closing {bot.user}')
    await bot.close()

data = DataClass()
if __name__=='__main__':
    bot.run(data.discord_token, log_handler=None)

this is how the std out looks like

2023-10-21 22:23:21 - __main__ - INFO - Starting Code
2023-10-21 22:23:25 - __main__ - INFO - We have logged in as stock-helper#6969
2023-10-21 22:23:25 - stock_helper.bot.run - INFO - Running error statement

and thats it. after this its like bot is stuck in infinite loop. no errors no exit. i would ideally like it to throw error and just shut down. can anyone guide me how to do that

shrewd fjord
unkempt canyonBOT
#

await on_error(event_method, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The default error handler provided by the client.

By default this logs to the library logger however it could be overridden to have a different implementation. Check [`on_error()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_error) for more details.

Changed in version 2.0: `event_method` parameter is now positional-only and instead of writing to `sys.stderr` it logs instead.
shrewd fjord
halcyon rapids
#

hi i did try this right now. and yes it gets there. i used this function

@bot.event
async def on_error(event):
    logger.info('ERROR')

here event is a string with value on_ready. any idea how can i print stack trace here and throw? this is what i get in stdout rn

2023-10-21 22:47:08 - __main__ - INFO - Starting Code
2023-10-21 22:47:11 - __main__ - INFO - We have logged in as stock-helper#6969
2023-10-21 22:47:11 - stock_helper.bot.run - INFO - Running error statement
2023-10-21 22:50:41 - __main__ - INFO - ERROR
halcyon rapids
shrewd fjord
#

now on error, you can exit or shutdown or whatever u want

shrewd fjord
#

to get the traceback

halcyon rapids
#

i put a try catch and it does the trick

shrewd fjord
#

nice...

halcyon rapids
#
@bot.event
async def on_ready():
    logger.info(f'We have logged in as {bot.user}')
    discord_helper = DiscordHelper(bot, actual_send=True)

    try:
        await run_bot(discord_helper, data)
    except Exception:
        traceback.print_exc()
        raise
    finally:
        logger.info(f'Closing {bot.user}')
        await bot.close()
#

thanks :3

shrewd fjord
#

np xd

devout drum
#

how i can get this to work?

hushed galleon
# devout drum how i can get this to work?

as in you only want the user to input a valid code? i suggest you write a transformer to validate it, for example: ```py
class WhitelistCodeTransformer(app_commands.Transformer):
async def transform(self, interaction, value: str) -> str:
if value not in codes:
raise ValueError("Invalid code")
# Above exception is wrapped in app_commands.TransformerError
# and can be handled by CommandTree.on_error
return value

WhitelistCode = app_commands.Transform[str, WhitelistCodeTransformer]

@bot.tree.command()
async def my_command(interaction, code: WhitelistCode):
...```

devout drum
hushed galleon
#

err, read the documentation and understand what it's doing

#

if you only need it once, you could be a bit more lazy and check it inside the command instead of using transformers

devout drum
#

async def wl(interaction:discord.Interaction, your_code: codes):

#

im tryna get that to work

hushed galleon
#

the only way to do it via typehinting is by writing a transformer

#

otherwise you can more simply ask them for an integer and then check codes[name] == your_code

#

btw i also suggest mapping the user's ID to their code so it doesn't break if they change their name

devout drum
hushed galleon
#

i guess it's not likely someone will change their name in between getting a code and using it, but generally you always want to use IDs instead of names as keys, because names change and IDs don't

shrewd apex
#

why did discord have to change their naming system ;-; it uses ids internally anyways

vague junco
#

how to launch a bot in the cmd?

slate swan
#

python file.py?

devout drum
#

how do i get this on my /command, how can i get a description like that

slate swan
#

!d discord.app_commands.CommandTree.command

unkempt canyonBOT
#

@command(*, name=..., description=..., nsfw=False, guild=..., guilds=..., auto_locale_strings=True, extras=...)```
A decorator that creates an application command from a regular function directly under this tree.
slate swan
#

description ^

humble lily
#

how do i solve?

stark nexus
mystic marsh
#

^

stark nexus
#

or no one will know where goes wrong in ur code

mystic marsh
#

then its bot = commands.Bot(...)

stark nexus
#

then do u know how can i solve this?

#

first one is code , second is error

mystic marsh
#

it says you have to await it
its await client.load_extention...

stark nexus
#

await ouside fuction

mystic marsh
#

you cant

#

use it in on_ready

stark nexus
slate swan
#

@fervent cove consider using discord.ext.tasks instead of manully doing it

mystic marsh
slate swan
#

You made your bot do some things each x seconds right

#

Theres a extension for that

fervent cove
#
async def send_daily_message():
    counter = 1
    await bot.wait_until_ready()
    while not bot.is_closed():
        now_hour = pytzdate.strftime('%H')
        if now_hour == '21':
            channel = bot.get_channel(1165374819651567707)
            await channel.send(f'{counter} days on!')
            counter += 1
        await asyncio.sleep(3600)```
slate swan
#

Yeah

fervent cove
#

this part - yes

slate swan
#

You dont have to do manually bot.is_closed etc anymore

fervent cove
#

oh

slate swan
#

Lemme find you a link

fervent cove
#

I would appriciate it ❤️

slate swan
#

There is now a special extension for just creating background loops:

from discord.ext import tasks

@tasks.loop(seconds=5)
async def my_loop():
    print('Hello World')

my_loop.start()```
The time until which the above loop will run is dependent upon human psychology, laws of energy and cosmos.
That is:
• You get bored of it
• The power goes down and your script stops working
• The universe explodes

Read more about it here: https://discordpy.readthedocs.io/en/latest/ext/tasks/
#

my_loop.stop() to stop it

#

But you gotta keep your bot online for it

#

(same for your current code)

fervent cove
#

Yeah, ik
This bot will be (I hope) online 24/7

slate swan
#

Okay

fervent cove
#
@tasks.loop(seconds=3600)
async def my_loop():
    counter = 1
    await bot.wait_until_ready()
    now_hour = pytzdate.strftime('%H')
    if now_hour == '21':
        channel = bot.get_channel(1165374819651567707)
        await channel.send(f'{counter} days on!')
        counter += 1

@bot.event
async def on_ready():
    channel_logi = bot.get_channel(1165360856335384656)
    print(f'{bot.user.display_name} online!')
    await channel_logi.send("I'm online!")
    print('Loading cogs . . .')
    for cog in cogs:
        try:
            await bot.load_extension(cog)
            print(f'{cog} was loaded.')
        except Exception as e:
            print(e)

    my_loop.start()```
#

@slate swan somtehing like this?

mystic marsh
#

just try it 🤷‍♂️

fervent cove
mystic marsh
#

its fine lol

fervent cove
#

And thanks a lot for advice!

hushed galleon
#

btw if you want to run it on a specific hour every day, you can use the time= argument instead of checking every hour py @tasks.loop(time=datetime.time(hour=19)) async def my_loop(): ...

slate swan
#

You dont need wait hntil ready, and why fo you place a check in my_loop if its daily (3600 seconds)

hushed galleon
#

also changing to tasks.loop means you'll need to store your counter variable somewhere else, such as an attribute on your bot

slate swan
#

ohhhhhhh thats why my bot throws so many errors having get_channel is None

#

HAha tysm

fervent cove
# hushed galleon btw if you want to run it on a specific hour every day, you can use the time= ar...

Traceback (most recent call last):
File "c:\Users\mnowa\Desktop\Discord Cogs Bot\main.py", line 29, in <module>
@tasks.loop(time=datetime.time(hour=19))
^^^^^^^^^^^^^^^^^^^^^^
TypeError: unbound method datetime.time() needs an argument

oupsi

code:

@tasks.loop(time=datetime.time(hour=19))
async def my_loop():
    counter = 1
    await bot.wait_until_ready()
    now_hour = pytzdate.strftime('%H')
    if now_hour == '00':
        channel = bot.get_channel(1165374819651567707) # counting-days-of-duty
        await channel.send(f'{counter} days on!')
        counter += 1``` did i put something wrong?
hushed galleon
#

oh i assumed you would write import datetime, not from datetime import datetime

fervent cove
#

I added import datetime, and still the same error occured

hushed galleon
#

did you remove the other import too?

#

and the counter still needs to be defined outside of the loop function, otherwise you'll be resetting it to 1 every time

fervent cove
# hushed galleon did you remove the other import too?

now it says:

Traceback (most recent call last): File "c:\Users\mnowa\Desktop\Discord Cogs Bot\main.py", line 16, in <module> pytzdate = datetime.now(pytz.timezone('Europe/Warsaw')) ^^^^^^^^^^^^ AttributeError: module 'datetime' has no attribute 'now'

slate swan
#

Change that line to datetime.datetime.now

#

Line 16

fervent cove
#

But it to get time from my time zone

slate swan
#

Because you changed from datetime import datetime to import datetime that line (16) now needs datetime.datetime

hushed galleon
#

sidenote, variable assignments don't magically repeat themselves, if you define the current time only once at the top of your file, it's going to be the same time forever (...until you re-run your script)

slate swan
#

Kinda weird they named it the same as the module

winter hare
#

is there a way to get multiple embeds sent using the same autocomplete code?

hushed galleon
slate swan
#

embed kwarg accepts list or no

#

in Messagable.send

hushed galleon
#

embeds= does, but not embed=

slate swan
#

yeah thx

fervent cove
# slate swan Because you changed from datetime import datetime to import datetime that line (...
day_counter = 1
@tasks.loop(time=datetime.time(hour=00))
async def my_loop():
    await bot.wait_until_ready()
    now_hour = pytzdate.strftime('%H')
    if now_hour == '00':
        channel = bot.get_channel(1165374819651567707) # counting-days-of-duty
        await channel.send(f'{day_counter} days on!')
        day_counter += 1```
I changed it to this, and it is not working ![92](https://cdn.discordapp.com/emojis/916495761007575050.webp?size=128 "92")
#

Line 16: pytzdate = datetime.datetime.now

slate swan
#

Nvmidk what is not working

hushed galleon
#

with time=datetime.time(hour=0), dpy will wait until 12AM of whatever timezone your system is in before it runs the loop

winter hare
hushed galleon
#

also due to variable scoping, you're going to get an UnboundLocalError when it attempts to assign day_counter += 1 because python isn't aware that it should be using day_counter from your global scope

slate swan
#

Save to bot var instead i dont think you can randomly save embed object to a json file

fervent cove
hushed galleon
winter hare
hushed galleon
hushed galleon
#

i guess you could have the user input multiple embeds at once like 1, 4, but i think that might be a bit unintuitive

winter hare
#

ok then select menu it is thanks for the suggestion and help

fervent cove
# hushed galleon im not sure what you mean by that because you were using pytz earlier just fine,...

Traceback (most recent call last): File "c:\Users\mnowa\Desktop\Discord Cogs Bot\main.py", line 30, in <module> @tasks.loop(time=datetime.time(hour=0, tzinfo=zoneinfo.ZoneInfo("Europe/Warsaw"))) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\mnowa\AppData\Local\Programs\Python\Python311\Lib\zoneinfo\_common.py", line 24, in load_tzdata raise ZoneInfoNotFoundError(f"No time zone found with key {key}") zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Europe/Warsaw'
sorry for being pain in the ass, but i copy/pasted it, and it's now working y4

hushed galleon
#

thanks windows, you gotta pip install tzdata beforehand (PyPI)

fervent cove
#
@tasks.loop(time=datetime.time(hour=00, tzinfo=zoneinfo.ZoneInfo("Europe/Warsaw")))
async def my_loop():
    day_counter = 1
    await bot.wait_until_ready()
    channel = bot.get_channel(1165374819651567707) # counting-days-of-duty
    await channel.send(f'{day_counter} days on!')
    day_counter += 1```
hushed galleon
#

yuh its gonna wait until 12AM

fervent cove
#

but it is 12AM now (in my timezone)

hushed galleon
#

oop i specifically mean 12:00:00AM, since that's the default for the minute and second if you don't type that in

fervent cove
#

OOH

#

That make sense

hushed galleon
#

for testing you can comment out the task.loop and put in @tasks.loop(seconds=30) or something

#

speaking of which the counter still can't be assigned inside the loop itself, otherwise you'll set it to 1 every time

fervent cove
#

nah, I'll wait 6 minutes and make some food while waiting 😂

hushed galleon
#

you can either define it as a global variable: ```py
count = 0

def my_loop():
global count
count += 1
print("The count is now:", count)or store it as an attribute on your bot, also known as "bot vars" which are more commonly suggested when it comes to discord.py:py
bot = commands.Bot(...)
bot.count = 0

def my_loop():
bot.count += 1
print("The count is now:", count)```

fervent cove
#

I'll use second option, thanks a lot for your advices ❤️

final iron
#

Tf is commands.Client

#

Anyway, run pip freeze and show the output

#

It doesn’t exist

#

Nice job showing like 25% of the output

#

?tag mb

novel apexBOT
#

This is not a Modmail thread.

final iron
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

final iron
#

Show all of it

#

Run pip list and screenshot the entire console

#

Your output isn’t possible

#

It’s missing all the standard libraries

golden portal
final iron
#

???

mystic marsh
#

choose one.

final iron
#

tfym lol

#

I literally told you what to do

golden portal
#

well from the screenshot it is installed, pycord and nextcord to be exact

final iron
#

me when it explicitly says py-cord

#

py-cord 2.4.1

rugged shadow
#

me when pystyle

naive briar
#

Is it just me or there's really no discord.py listed there

obtuse pumice
#

Can anyone help me in js

golden portal
#

its best if you ask in a javascript server instead

shrewd fjord
#

assuming you are asking help about a discord bot written in js

obtuse pumice
void whale
#

why is this not working but if i use this py -m pip install discord.py it does is affecting my code?

slate swan
#

can someone help me

#

im going to kill myself bro

rotund flame
#

dude that is an node js bot wtf

slate swan
#

nice

#

so?

#

@rotund flame

rotund flame
#

so, this is a python server, not a java script server

robust fulcrum
fading linden
#

does a discord bot require admin access to be able to edit people's messages?

fading linden
#

yea

naive briar
#

There's no such thing

fading linden
#

i tried and it does say forbidden
but idk if it means it needs admin access or some other permission in the developer portal

slate swan
#

@fading linden you can edit your bots messages but cant edit other peoples

vocal rivet
#

TypeError: 'SequenceProxy' object is not callable

@bot.command()
async def drs(ctx):
    guild = ctx.guild

    for role in guild.roles():
        await role.delete()

    print(f"Deleted all roles.")```
slate swan
#

Try guild.roles

#

Instead of guild.roles()

vocal rivet
#
@bot.command()
async def cs(ctx):
    await ctx.message.delete()

    guild = ctx.guild
    tGuild = bot.get_guild(1157974109200850944)

    for role in guild.roles:
        await tGuild.create_role(name=role.name, permissions=role.permissions, colour=role.colour)

    print("> Roles duplicated successfully.")```

It works but it duplicates the roles upside down, is there a way to duplicate the roles from the last to the first?
vocal rivet
slate swan
#

reverse the list?

meager rock
#

Remember that this will create an extra role named @everyone in the server ( other than the real one )

vocal rivet
slate swan
#

List.reverse() right

#

guild.roles[::-1]

vocal rivet
slate swan
#

same thing

#

reverses it

#

!e ```py
x = [1, 2, 3]
print(x[::-1])

unkempt canyonBOT
#

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

[3, 2, 1]
meager rock
#

!e ```py
print([1,2,3,4][::-1])

unkempt canyonBOT
#

@meager rock :white_check_mark: Your 3.12 eval job has completed with return code 0.

[4, 3, 2, 1]
vocal rivet
#

Ooo ok thank you

slate swan
#

and you most likely want to omit the everyone role s

#

so something like [1::-1] could work

vocal rivet
#

What does the 1 and the -1 stand for?

#

Is there a document for this ?

slate swan
#

!slicing

unkempt canyonBOT
#
Sequence slicing

Slicing is a way of accessing a part of a sequence by specifying a start, stop, and step. As with normal indexing, negative numbers can be used to count backwards.

Examples

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters[2:]  # from element 2 to the end
['c', 'd', 'e', 'f', 'g']
>>> letters[:4]  # up to element 4
['a', 'b', 'c', 'd']
>>> letters[3:5]  # elements 3 and 4 -- the right bound is not included
['d', 'e']
>>> letters[2:-1:2]  # Every other element between 2 and the last
['c', 'e']
>>> letters[::-1]  # The whole list in reverse
['g', 'f', 'e', 'd', 'c', 'b', 'a']
>>> words = "Hello world!"
>>> words[2:7]  # Strings are also sequences
"llo w"
vocal rivet
#

Thank you

fading linden
#

thanks

naive briar
fading linden
vocal rivet
#

TypeError: 'CategoryChannel' object is not iterable

    for category in guild.categories:
        newCategory = await tGuild.create_category(name=category.name)
        for channel in category:
            await tGuild.create_text_channel(name=channel.name, category=newCategory)```
#

I'm trying to copy channels and their categories from one discord server to another

#

Any idea how to fix this issue?

slate swan
#

for channel in category.channels @vocal rivet

vocal rivet
stark nexus
#

anyone could help me to solve an issue of my minigame bot?

Command (slash command) :

@client.hybrid_command(description='The commands this bot use')
async def game(ctx):
    if (ctx.message.author in authors or ctx.message.author in rivals):
      return
    authors.append(ctx.message.author)
    rivals.append("wait")
    games.append("wait")

    embed = discord.Embed(title=tfname,
                          description="@here " + ctx.message.author.name +
                          " waiting for a rival...",
                          color=0x2B32E4)
    msg = await ctx.send(embed=embed)
    msgs.append(msg)
    await msg.add_reaction("🆚")
stark nexus
#

Anyone could let me solve that?

#

Error

#

(The error happened without "ctx" im using trying to solve it but failed

slate swan
#

you dont have context in events

stark nexus
slate swan
#

i mean you dont get ctx as argument in events

#
@client.event
async def on_reaction_add(reaction, user):
``` so you cant use it inside
#

you already have a reaction so why try ctx.reaction

stark nexus
#

So i have to edit entite code?

slate swan
#

no, why?

stark nexus
slate swan
#

reaction.emoji is a string then

#

print out reaction.emoji

slate swan
#

how can i make a $dmall {message} command?

#

Step 1: You don't as Discord doesn't like it at all

quaint agate
#

try printing it and you would see a unicode emoji in console

stark nexus
slate swan
#

oh im dumb

#

forgot to define it

slate swan
#

Ignoring step 1 and 2 will eventually get your bot banned thumbsup

fiery girder
#

hey

#

is there a way i can tell if there is a member mentioned in a message using discord.py

slate swan
#

!d discord.Message.mentions

unkempt canyonBOT
#

A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.

Warning

The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.

slate swan
#

how can i fix?

shrewd fjord
slate swan
#

it sends two embeds

#

for some reason

#

i didnt even code the first one 💀

nimble jetty
#

Wow!!

slate swan
#

like when i send a command it runs it 2 times

slate swan
#

unfortunate

slate swan
#

yeah

#

but i need to fix it

#

found the issue

#

dw

slate swan
#

how can i add an image like that in the title of the embed?

wicked atlas
#

That is the author attribute of an embed

#

!d discord.Embed.set_author

unkempt canyonBOT
#

set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.

This function returns the class instance to allow for fluent-style chaining.
wicked atlas
#

icon_url can be set to the link of the image you want to display

slate swan
#

Like that?

naive briar
#

Remove the *,, that's the argument's signature

slate swan
#

What about the name?

naive briar
#

Set it to whatever you want

slate swan
#

Where does it display it

#

?

naive briar
#

At the right side of the icon

slate swan
#

like the "Message Deleted"?

naive briar
#

Yes?

slate swan
#

alr

#

alr

cold sonnet
#

alr

slate swan
#

alr

cold sonnet
#

define Ticket alr

snow breach
#

i have a problem with my bot

#

can someone help me?

slate swan
cold sonnet
#

Ticket =

#

alr

twin cedar
#

anyone here

slate swan
#

where

#

alr

cold sonnet
#

bro

#

there's levels of not knowing programming alr

slate swan
#

why would i need to define it

twin cedar
#

bro i have a problem can you fix it

slate swan
#

its a name why would i need to define it

cold sonnet
slate swan
#

like this?

twin cedar
#

@jaunty sparrow

slate swan
twin cedar
#

ok

cold sonnet
slate swan
#

i have it like that

#

got an unexpected keyword argument 'Name'

#
embed.set_author(Name="Ticket", url=None, icon_url="icon_link")
cold sonnet
#

it's name= not Name= bro

slate swan
#

I FORGOR

cold sonnet
#

don't forger next time

slate swan
#

i wont forgor

cold sonnet
#

alr

slate swan
#

alrr

vale wing
#

I think these calculations are correct

sick birch
vale wing
#

Almost 400 servers

sick birch
#

cute

#

🥺

vale wing
#

How the hell do we promote it

#

Made a video that contained its promotional and it gathered 25k views, still no gain

void whale
naive briar
#

yarl (aiohttp's dependency) doesn't support 3.12 yet

rotund flame
#

esnoobCuteS windows PATH kicks in

rotund flame
#

switch to windows prompt

#

and see if works

final iron
obtuse pumice
#

HTTPError [AbortError]: The user aborted a request.

#

how to fix these error

void whale
#

also how do i get out of powershell

brazen raft
#

If you've entered it by running the command powershell on Command Prompt, you should be fine using exit to get out of the PowerShell session. If you've entered it directly otherwise, you should be able to simply close the window of it or the tab of it if you're using Terminal

final iron
obtuse pumice
#

When I send request from discord

#

To server

void whale
brazen raft
obtuse pumice
#

@final iron

brazen raft
#

This chain of messages turned into something which fits #editors-ides's topic by the way

next heath
#

Can someone help me whit this code.
I whant to unban in a difrent server
Code:

@client.command()
async def unban(ctx, Userid:discord.User, *, reason=None):
    await ctx.message.delete()
    server = client.get_guild(1148073800374693908)
    await server.guild.unban(Userid, reason=reason)
    
    await Userid.send(f"Memmber got Unbanned **User**: {Userid.mention} **UserId**: {Userid} **Reason**: {reason} unbanned by: {ctx.author.mention}")
brazen raft
#

Consequently, it might be a good idea to rename Userid to something sensible like member

next heath
#

I run the command from a server The comunety has a ban server and a main server so i need to find the main server then unban

final iron
#

server.guild.unban(Userid, reason=reason) what

brazen raft
#

It'll do the job as long as the command is run from a server and is meant to unban members from the same server it's run

#

What you're trying to do seems impossible without getting the guild

#

But what's the problem with your current code?

unkempt canyonBOT
#
Nope.

No documentation found for the requested symbol.

slate swan
#

As you can see, a guild has no guild attribute

#

So doing server.guild won't work - and naming a guild object server isn't really a correct naming convention either.

final iron
#

I started just ignoring naming conventions while helping a long time ago

#

It's an unhill battle you'll never win

#

So many people just refuse to properly name things for some reason

vague junco
#
@commands.command(name="uptime", description="Отправить информацию о аптайме бота в канал.", help="Аптайм бота.", nsfw=False, aliases=["ut"], hidden=False, brief="Аптайм бота.", usage="!uptime", guild_only=False, enabled=True)
    async def _uptime(self, ctx: commands.Context) -> Message:
        """
        Отправить информацию о аптайме бота в канал.

        Parameters:
            ctx (commands.Context): The context of the command.

        Returns:
            discord.Message: The message sent by the bot indicating the result of the operation.

        Raises:
            Exception: If an error occurs during the execution of the command.
            discord.HTTPException: If an HTTP-related error occurs during the execution of the command.
            commands.MissingPermissions: If the bot is missing permissions required to execute the command.
        """
        try:
            current_time = datetime.datetime.utcnow()
            botuptime = current_time - start_time

            minutes, seconds = divmod(botuptime.total_seconds(), 60)
            hours, minutes = divmod(minutes, 60)
            days, hours = divmod(hours, 24)

            uptime_str = f"{int(days)}d {int(hours)}h {int(minutes)}m {int(seconds)}s"

            return await ctx.send(embed=discord.Embed(title="Аптайм", description=f"**{uptime_str}**", color=discord.Color.yellow()))

        except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
            return await issue_msg(e, ctx)  # Handle any exceptions that occur during the execution of the command

how do I make an application command for this?

slate swan
#

Same way you do normally

#

Read the docs on how to make an app command

cold oyster
#

use 3.10.5, its the best

final iron
cold oyster
final iron
cold oyster
#

Does anyone of you know how to make the thing in dank memers' bio? So basically if you look at his bio in a server it will show a /rob command and if you click it, It puts the command in the type bar

#

Also the try my commands thing

cold oyster
final iron
#

Literal[] is pretty self explanitory and iirc Enum would be like this

class MusicStreamingSites(Enum):
    youtube = ""
    spotify = ""

async def my_command(interaction: discord.Interaction, site: MusicStreamingSites) -> None:
    pass
next heath
vague junco
#
    @hybrid_command(name="ping", description="Отправить информацию о пинге бота в канал.", with_app_command=True, help="Пинг бота.", nsfw=False, hidden=False, brief="Пинг бота.", usage="!ping", guild_only=False, enabled=True)
    async def _ping(self, ctx: commands.Context) -> Message:

        try:
            return await ctx.send(f"Pong! {round(self.bot.latency * 1000)}ms")

        except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
            return await issue_msg(e, ctx)  # Handle any exceptions that occur during the execution of the command

will this command be executed as an app command? ( /ping )

vague junco
final iron
#

Yes, that's the whole point of hybrid commands

robust fulcrum
vague junco
robust fulcrum
#

from enum module

cold oyster
robust fulcrum
turbid condor
drifting arrow
#

Out of curiosity, is it possible for a discordbot to read a webhook embed?

hushed galleon
drifting arrow
hushed galleon
naive briar
#

!d discord.Webhook.send

unkempt canyonBOT
#
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message using the webhook.

The content must be a type that can convert to a string through `str(content)`.

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object.

If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects to send.

Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
shrewd fjord
#

huh we can changer user name and avatar while sending a message w webhook? never knew

shrewd fjord
vale wing
shrewd fjord
#

oh cul

slate swan
#

How can I make a menu like this?

golden portal
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0.

Examples...
slate swan
#

Ty

#

When the user presses submit

#

I want it to send his application to a channel

#

And 2 buttons 1. Approve 2. Decline

#

If the admin presses approve I want it to add a specific role to the user that made the application

#

And to send him a dm

#

Is it possible?

golden portal
#

yes, the Modal triggers on_submit callback when the user submit, then you can just send a message to that specific channel with a view where it contains discord.ui.Button

slate swan
#

How will I tell to the bot to add him roles

#

U can't do interaction.user

golden portal
#

you can do interaction.user, it's a discord.Member if it's in a guild

slate swan
golden portal
# slate swan But, won't the bot think that interaction.user is the user that approved a modal...

oh you mean that, you would have to store the member object when you send the view, i.e ```py
class MyModal(discord.ui.Modal):
async def on_submit(self, interaction):
...
member = interaction.user
await interaction.response.defer()
await channel.send(f"This user {member} is asking for approval blah blah", view=MyView(member))

class MyView(discord.ui.View):
def init(self, member):
super().init()
self.member = member
@discord.ui.button(label="Approve")
async def on_approve(self, interaction, button):
print("you have access it here", self.member)

#

you get the idea

slate swan
slate swan
#

Alright

#

Could you remove them from the class and just use the async def? I really don't use classes

golden portal
#

no they are class based, it was designed this way

slate swan
#

Oh

#

Alright

graceful temple
#

send a message when someone boost?
can someone help me

slate swan
unkempt canyonBOT
#

discord.on_guild_update(before, after)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) updates, for example:

• Changed name

• Changed AFK channel

• Changed AFK timeout

• etc...
graceful temple
slate swan
# unkempt canyon

I'm not actually certain this gets called when someone boosts though. If it doesn't then another way could be to check members' roles for the booster role in on_member_update

slate swan
shrewd fjord
#

but yeah prefer using class

graceful temple
#

thank you tho :)

shrewd fjord
#

!d discord.Member.premium_since

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.

shrewd fjord
#

for tracking the boost 2nd time

slate swan
#

How do i turn a mention e.g. @slate swan into the text version @genx?

slate swan
#

I got it nvm, method i was looking for was Message.clean_content

final iron
#

Is it possible to add roles to a user using the raw API?

final iron
#

What would the endpoint be?

sick birch
unkempt canyonBOT
#

discord/http.py lines 1855 to 1865

def add_role(
    self, guild_id: Snowflake, user_id: Snowflake, role_id: Snowflake, *, reason: Optional[str] = None
) -> Response[None]:
    r = Route(
        'PUT',
        '/guilds/{guild_id}/members/{user_id}/roles/{role_id}',
        guild_id=guild_id,
        user_id=user_id,
        role_id=role_id,
    )
    return self.request(r, reason=reason)```
final iron
#

Tyty

lyric sigil
#
ModuleNotFoundError: No module named 'Cogs'
#

How do i fix this error

#
Collecting Cogs==0.3.0
  Downloading Cogs-0.3.0.tar.gz (17 kB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error
  
  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [3 lines of output]
      /usr/local/lib/python3.10/site-packages/setuptools/dist.py:286: SetuptoolsDeprecationWarning: The namespace_packages parameter is deprecated, consider using implicit namespaces instead (PEP 420).
        warnings.warn(msg, SetuptoolsDeprecationWarning)
      error in Cogs setup command: use_2to3 is invalid.
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed
× Encountered error while generating package metadata.
╰─> See above for output.
note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Logs

slate swan
#

!pypi Cogs

unkempt canyonBOT
#

Toolkit for developing command-line utilities in Python

slate swan
#

Why do you need that for a bot

lyric sigil
#

A ticket system bot

slate swan
#

Doesn't answer my question

lyric sigil
#

LIke i dont really know

#

Its a friend code

#

that he gave to me

slate swan
#

Ask your friend then

lyric sigil
#

Not online

slate swan
#

Have patience

lyric sigil
#

Also it's not working

#

Same error

#

My setup on pterodactyl

slate swan
#

I know, that's why I'm asking why you need that

#

It's outdated and even deleted

lyric sigil
#

bruh

slate swan
#

And if you can't answer, ask your friend

final iron
lyric sigil
#

IDK mate

#

Want me to send the code

final iron
lyric sigil
#

DOn't have time to read all the code

final iron
#

You know most editors have a search function right

lyric sigil
#

Only thing i've founded :

from cogs.ticket_system import MyView
#

And others Lines like this

#

TO import some functions to the main file

final iron
#

And the functions were never used?

lyric sigil
#

Yes they were

final iron
#

Show the usage

#

Also are you sure cogs isn’t a local file?

#

The pypi package is uppercase, while the import is lowercase

lyric sigil
#

Sended all the code in dm

final iron
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

lyric sigil
#

Okay here is the files who has code in them

vague junco
#
@hybrid_command(name="announce", description="Отправить объявление от имени бота в указанный канал.", with_app_command=True, help="Отправить объявление.", nsfw=False, hidden=False, brief="Объявление.", usage="!announce <канал> <объявление>", guild_only=False, enabled=True)
    @commands.has_permissions(manage_messages=True)
    async def _announce(self, ctx: commands.Context, channel: discord.TextChannel = None, *, message: str = None) -> Message:
        """
        Отправить объявление от имени бота в указанный канал.

        Parameters:
            ctx (commands.Context): The context of the command.
            channel (discord.TextChannel, optional): Channel to send the message.
            message (str, optional): Message to send.

        Returns:
            discord.Message: The message sent by the bot indicating the result of the operation.

        Raises:
            Exception: If an error occurs during the execution of the command.
            discord.HTTPException: If an HTTP-related error occurs during the execution of the command.
            commands.MissingPermissions: If the bot is missing permissions required to execute the command.
        """
        try:
            if channel is None or channel not in ctx.guild.channels:
                return await ctx.send(embed=discord.Embed(description="Укажите канал, куда отправить объявление!", color=discord.Color.red()))

            if message is None:
                return await ctx.send(embed=discord.Embed(description="Укажите сообщение, которое отправить объявлением!", color=discord.Color.red()))

            embed = discord.Embed(title="Объявление", description=f"{message}", color=discord.Color.green())
            embed.set_author(name=ctx.author.name, icon_url=ctx.author.avatar)

            return await channel.send(embed=embed)

        except (Exception, discord.HTTPException, commands.MissingPermissions) as e:
            return await issue_msg(e, ctx)  # Handle any exceptions that occur during the execution of the command

how do I make arguments mandatory in an application command?

solar glen
#

is there a way to specify on a avatar_url, a byte sequence to take in as a image instead of having to actually use a url(Its pycord but i think the premise still applies to discord.py since pycord is a fork of it)

#

or just a file with BytesIO

shrewd apex
vague junco
velvet tinsel
#

how do you reply to a message in an on_message event?

patent lark
#

I need help , i have written a warn command, and whenevr i mention a member, member returns None no matter what. Can anyone give me some advice?

patent lark
#

!d discord.Message.reply

unkempt canyonBOT
#

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

A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message).

New in version 1.6.

Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
velvet tinsel
patent lark
#

mhm

final iron
patent lark
steep jay
#

Why does my terminal sends this error: note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects

vocal rivet
#

How can I change my own bot's nickname ?

final iron
unkempt canyonBOT
#

await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., bypass_verification=..., 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...
final iron
#

nick kwarg

devout drum
#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.

cold oyster
#

!codeblock

unkempt canyonBOT
#
Formatting code on discord

Here's how to format Python code on Discord:

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

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

For long code samples, you can use our pastebin.

clear lark
#

Select Menus are supposed to show you what you've selected right?

hushed galleon
#

and i thought it was super annoying, it wont let you pick the same option twice

clear lark
#

(for me and my friends)
Desktop is not showing your selections and it lets you select it infinitely, which isn't too big a problem for my use case, but I was curious if that was intended or not

hushed galleon
#

you can manually reset it by editing the message with the view= argument tho

clear lark
hushed galleon
south coyote
#

i shut down all my bots running in the terminal but they are still running in the server

#

ad taking commands

burnt idol
#

Any free vps services for hosting python bots

vocal rivet
#
    for category in guild.categories:
        newCategory = await tGuild.create_category(name=category.name, overwrites=category.overwrites)
        for channel in category.channels:
            if type(channel) == discord.channel.TextChannel:
                dupedChannel = await tGuild.create_text_channel(name=channel.name, category=newCategory, overwrites=channel.overwrites)

            elif type(channel) == discord.channel.VoiceChannel:
                await tGuild.create_voice_channel(name=channel.name, category=newCategory, overwrites=channel.overwrites)```

It's not applying the channel and categoy overrwrites, any idea why?
vocal rivet
shrewd apex
#

lmao

shrewd apex
vocal rivet
#

o

#

right

slate swan
#

i want help related to telegram bot, in which channel should i ask for help??

dry oak
hallow kernel
#

Can i remove from @ everyone ability to use emojis from my server?