#discord-bots

1 messages · Page 181 of 1

shut elk
#

ok

lusty smelt
#

IMO defer first wont hurt anything.

shut elk
#

ok

#

thank you 👍

lusty smelt
#

Ahh.. I dont deserve that.. haha.. I feel like I lead you astray with my lack of understanding.

#
pymongo.errors.CursorNotFound: cursor id 3343587727049317749 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 3343587727049317749 not found', 'code': 43, 'codeName': 'CursorNotFound', '$clusterTime': {'clusterTime': Timestamp(1673983973, 3), 'signature': {'hash': b'}\r\x05o\xfejJ\x87!6\xf7?P\xa0\xb3\x00\xf7\xbf\x8fs', 'keyId': 7127295041399160841}}, 'operationTime': Timestamp(1673983973, 3)}
``` That is your entire error.
young dagger
lusty smelt
#

I stand corrected.. googled the error.

#

You are timing out.

shut elk
# lusty smelt Ahh.. I dont deserve that.. haha.. I feel like I lead you astray with my lack of...

nah, i've been dealing with this like for multiple days and asked multiple people, i think it might just be my server being too slow along with my messy code that is causing the problem. Probably will revamp when I have more free time but at the moment ill probably leave it as it is. It isn't causing much problems, it is just making one ort wo buttons not work every like 12 hours so it should be fine

young dagger
shut elk
#

Thanks for ur help tho lol

young dagger
#

To close the cursor

lusty smelt
# young dagger The cursor id is different each time.

per their docs.
Cursors in MongoDB can timeout on the server if they’ve been open for a long time without any operations being performed on them. This can lead to an CursorNotFound exception being raised when attempting to iterate the cursor.

sick birch
#

You're using pymongo, right?

young dagger
young dagger
sick birch
#

Pymongo is a blocking client

#

And when you do long blocking I/O things start getting funky in an asynchronous environment

#

It blocks your entire event loop from running

#

discord.py can no longer heartbeat the gateway, gets disconnected, and overall spotty connection

#

!pypi motor

unkempt canyonBOT
sick birch
#

For an asynchronous alternative

naive briar
#

Some people already told him about that yert

lusty smelt
#

Shows how stupid I am 😛

young dagger
sick birch
#

I just popped in lol

sick birch
#

Asynchronous programming, at least in Python, is not truly "parallel"

#

It uses just 1 thread, which is why things that block the entire thread (such as time.sleep() or blocking I/O clients like pymongo) can be problematic

young dagger
#

@sick birch Can you please explain why I'm not seeing the error anymore with users.close()?

In the following code:

@tasks.loop(hours=24)
async def update_elo_ratings():
    print("Updating all users from the database...")
    # Get all the users in the collection
    users = collection.find()
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(2)
    users.close()
    print("Finished updating all users from the database.")
sick birch
#

Looks like some syntax errors are going on there

#

Is that just Discord or in your code?

young dagger
sick birch
#

Yeah looks to be an unclosed quotation

young dagger
young dagger
sick birch
#

As per your original question -
users was probably some sort of cursor object, when it was not closed, you were keeping an I/O operation open for a long time

young dagger
sick birch
#

It will require a significant rewrite unfortunately

#

Better now than later down the road with a larger codebase

young dagger
sick birch
#

Oh is it?

#

I haven't heard

young dagger
sick birch
#

It's not bad it's just not the right tool for the job

#

A screwdriver is not bad because you can't slice bread with them 😛

pliant gulch
#

Where did you hear about motor being un-maintained/retired?

#

There was literally a PR merged a week ago

sick birch
#

No currently active PRs or issues though 🤔
Guessing that's because they're just on top of things

young dagger
pliant gulch
#

Guy's a type machine

young dagger
naive briar
#

That's okay

velvet sierra
#

someone know how i can get a text from TextInput?

naive briar
#

!d discord.ui.TextInput.value

unkempt canyonBOT
velvet sierra
#

ty

potent spear
#

note about document based dbs^

young dagger
#

Or should I use it to stop the I/O operation?

sick birch
#

Or if motor provides a context manager (like aiosqlite) does, you won't have to manually

young dagger
#

Ok thanks

spiral crypt
#

Error: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In emoji_id: Value "" is not snowflake.
What does this mean in the context of this code

await message.add_reaction(f":{num2words.num2words(i+1)}:")
torpid dew
#
Traceback (most recent call last):
  File "main.py", line 8, in <module>
    from discord import app_commands
ImportError: cannot import name 'app_commands' from 'discord' (/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/init.py)
#

why wont it import

sick birch
torpid dew
#

oh

torpid dew
spiral crypt
#

then it says "Error: Command raised an exception: HTTPException: 400 Bad Request (error code: 10014): Unknown Emoji" o:

sick birch
#

What IDE are you using?

sick birch
spiral crypt
#

default

sick birch
#

Can we see them?

spiral crypt
#

1️⃣2️⃣3️⃣ etc

torpid dew
#

repl

torpid dew
sick birch
torpid dew
#

thx

sick birch
spiral crypt
#

oh, is there a way to do it like, with numbers because its in a for loop that can iterate anywhere from 2-9

#

or do i have to do it using a list of the emoji strings

sick birch
#
emojis = ["1️⃣", "2️⃣", "3️⃣", ...]
spiral crypt
#

gotcha

jaunty hare
#

hi! someone has a little code of aiosqlite? i dont understand nothing of documentation and idk what to do

sick birch
# jaunty hare hi! someone has a little code of aiosqlite? i dont understand nothing of documen...

Here's an example of how you'd integrate aiosqlite with discord.py. This is just a framework I'd like you to off of rather than copy and pasting (it most likely won't work if you do that)

class MyBot(commands.Bot):
  def setup_hook(self) -> None:
    self.db = await aiosqlite.connect("filename.db")

bot = MyBot(command_prefix="!", intents=discord.Intents.all())

@bot.command()
async def db_operation(self, ctx: commands.Context, ...) -> None:
  async with bot.db.execute("<SQL QUERY HERE>") as cursor:
    # operate on `cursor`
  await ctx.send("Database operation complete!")

bot.run()
jaunty hare
#

thank u

velvet sierra
#

someone know how i can send a modal after someone click in one button?

sick birch
#

!d discord.InteractionResponse.send_modal

unkempt canyonBOT
#

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

Responds to this interaction by sending a modal.
velvet sierra
sick birch
#

What error?

velvet sierra
sick birch
#

Can you show us your code?

velvet sierra
#

i cant bc it has some personal things inside

sick birch
#

We can't really help then

hushed galleon
#

usually means the callback timed out doesnt it

sick birch
#

Yeah

#

You have 3 seconds to respond to an interaction

#

If it takes longer you can defer()

hushed galleon
#

well, in the case of a modal you cant defer

velvet sierra
#
        class Mymodal(discord.ui.Modal, title='z'):
            answer = discord.ui.TextInput(label='t', style=discord.TextStyle.short, required = True, placeholder='q')
            async def on_submit(self, interaction):
                await interaction.response.send_message('k')
                if str(c) == str(d):
                    await interaction.response.send_message('a')
                else:
                    await interaction.response.send_message('b')
        class Button(discord.ui.View):
            @discord.ui.button(label="x", style=discord.ButtonStyle.green, emoji="y")
            async def mybutton(self, interaction, button):
                 ...
                await interaction.response.defer()
                await asyncio.sleep(1)
                await interaction.response.send_modal(Mymodal(timeout=None))
#

looks like the defer did not solved, that just gived me a different error:

discord.errors.InteractionResponded: This interaction has already been responded to before
slate swan
#

you can't defer

#

and then send a modal @velvet sierra

#

i suggest not sending a modal at the end if ur doing a bunch of shit

#

create a seperate buttoni

#

to send a modal

velvet sierra
glad dock
#

Since discord.py is an ascio loop, does that mean anything inside of the bot script would be ran constantly as well?

#

Can I make it infinitely print things?

slate swan
#

no its not

torn sail
#

There is member.guild_permissions but you may be looking for channel.permissions_for(member)

slate swan
#

what do u mean top 3?

#

permissions aren't ordered in any specific way

#

that doesn't exist with user permissions.

#

yea u got some custom stuff going on

#

owner by default has all perms

#

how is your most_common func setup?

#

im assuming it just gets all member perms from guild and counts each perm and gets the lowest count perm?

#

well u have .most_common

#

but u said u wanted least common

#

well cause

#

roles override those permissions

#

u should check role permissions rather than individual perms

sick birch
#

day in the life of a programmer

craggy sleet
#

does anyone know how to call a discord bot's command but through a website?

#

i need to access some discord info through my website and was wondering if there was a way

slate swan
#

use a database

#

or make an api

craggy sleet
#

how would i make an api for discord bot commands

slate swan
#

the command is still a function

#

just call the function

craggy sleet
#

youd have to run both the web framework and the discord bot client in the same file tho

#

im not sure

slate swan
#

not exactly. your best bet tho is using a database

#

especially if you just need to access data

craggy sleet
#

well, what i was aiming for was checking if a user was in a server

slate swan
#

just use oauth?

craggy sleet
#

then they get access to different things on the website

#

hm thats true

slate swan
#

u can see all servers the user is in as well as mutual servers

craggy sleet
#

makes sense

#

thanks

slate swan
#

yup

naive briar
#

Why

#

Just set it normally

craggy sleet
tough lance
#

Hi, what is the best way to keep a discord bot script running in Ubuntu

naive briar
tough lance
slate swan
vale wing
#

Containerising application is better than just running it

tough lance
#

Well I was using nohup before but my bot was crashing for no reason.

#

No error message. I thought it was a memory leak, but it wasn't

vale wing
vale wing
tough lance
#

Like killed by OOM killer

#

I saw in system logs it was before, and I fixed it, but now it is crashing even with low memory usage

slate swan
#

Anyone know best hosting website for discord.py bot & pycord

naive briar
slate swan
agile lark
#

Am i dumb, or what?

  File "/home/hedmad/Files/repos/Milton/milton/cogs/math_render.py", line 71, in on_message
    await self.bot.wait_for("reaction_add", timeout=300, check=event_check)
TypeError: Client.wait_for() missing 1 required positional argument: 'event'
#

The "reaction_add" is the event?

#

The signature is wait_for(event, /, *, check=None, timeout=None)...?

#

Ok - nevermind. I'm just an idiot

vale wing
tough lance
vale wing
#

Perhaps you meant memory overuse

tough lance
#

What's the difference? asking genuinely

#

Like memory building up overtime isn't memory leak?

vale wing
#

Memory overuse is when you exceed amount of RAM available, memory leak is program issue that leaves unused stuff in memory

tough lance
#

My problem was that buffers weren't closed

#

So that was a memory leak

vale wing
#

To be more precise "memory for object you finished operating with was never deallocated"

vale wing
vale wing
tough lance
vale wing
#

Python has garbage collector, there can't be memory leaks 💀

#

Unless it acts dumb

tough lance
#

I used tracemalloc to pinpoint it

vale wing
#

Anyways your problem is in different thing

tough lance
vale wing
#

You used nohup?

tough lance
#

Ya

#

My bot is in ~1.8k servers btw

vale wing
#

Follow my guide instead and use docker

tough lance
vale wing
#

Docker isn't gonna affect its performance

slate swan
#
@bot.slash_command()
async def banner(ctx, user:discord.Member):
    user = await bot.fetch_user(user.id)
    banner_url = user.banner.url
    embed = discord.Embed(title=f"{user.name}'s Banner", color=0xFF0000)
    embed.set_image(url='{}'.format(banner_url))
    await ctx.send(embed=embed)```
I just notice something here updated code 😅
vale wing
#
"{}".format(string_instance)```
is the most useless thing I've ever seen, no offense
#

Why not do url=banner_url bruh

oak warren
#

i am trying to add easy_pil for my discord bot via poetry but for some reason it cant recognize the package

#

what do i do

#

like it ads it but then it gives some error related to aiohttp

unkempt canyonBOT
naive briar
slate swan
#
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 851, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "C:\Users\user\Desktop\Other\Bots_For_Sell\cleevno\bot.py", line 97, in ea
    await interaction.guild.create_custom_emoji(name="emoji1",image=img)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 3010, in create_custom_emoji
    img = utils._bytes_to_base64_data(image)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 612, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 598, in _get_mime_type_for_image
    if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
AttributeError: 'File' object has no attribute 'startswith'

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

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\tree.py", line 1240, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 876, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 869, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'ea' raised an exception: AttributeError: 'File' object has no attribute 'startswith'```
oak warren
#

oh its a -

#

let me try again

#

i downgraded my aiohttp and i am trying again

slate swan
# slate swan ```[2023-01-18 13:58:55] [ERROR ] discord.app_commands.tree: Ignoring exceptio...

code :

@app_commands.describe()
async def ea(interaction:discord.Interaction):
    def check(reaction, user):
        return user == interaction.user
    await interaction.response.send_message('**Please react to this message with the emoji you want to add**', ephemeral=False)
    the_reaction = await bot.wait_for('reaction_add', check=check)
    await the_reaction[0].emoji.save("1.png")
    img = discord.File("1.png")
    await interaction.guild.create_custom_emoji(name="emoji1",image=img)
    print("Done")```
naive briar
unkempt canyonBOT
#

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

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

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

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

Not discord.File, read the docs

oak warren
# oak warren i downgraded my aiohttp and i am trying again
Because no versions of easy-pil match >0.1.9,<0.2.0
   and easy-pil (0.1.9) depends on aiohttp (>=3.6.0,<=3.8.1), easy-pil (>=0.1.9,<0.2.0) requires aiohttp (>=3.6.0,<=3.8.1).
  And because discord (rev master) depends on aiohttp (>=3.8.2,<4.0), easy-pil (>=0.1.9,<0.2.0) is incompatible with discord (rev master).
  So, because project depends on both discord (branch master) and easy-pil (^0.1.9), version solving failed.

  at /opt/virtualenvs/python3/lib/python3.8/site-packages/poetry/puzzle/solver.py:241 in _solve
      237│             packages = result.packages
      238except OverrideNeeded as e:
      239return self.solve_in_compatibility_mode(e.overrides, use_latest=use_latest)
      240except SolveFailure as e:
    → 241raise SolverProblemError(e)
      242243│         results = dict(
      244│             depth_first_search(
      245│                 PackageNode(self._package, packages), aggregate_package_nodes```
naive briar
oak warren
#

its in requirements.txt

naive briar
#

Just git clone it then remove the requirement

slate swan
#

@naive briarthanks it worked

naive briar
#

Or literally just use Pillow

oak warren
#

my code is kinda complete for it

#

it used to work but now they changed it

glad cradle
#

you could switch back to an older version

slate swan
#

wait actually its' the famous replit issue lol

#

just create a new repl ig

oak warren
#

yea sadly

#

hmm okay

jagged quartz
#

???

heady verge
#

is there any option where if the user who is executing the command doesnt have a guild avatar so that we can disable a button?

slate swan
#
  File "c:\Users\maxje\Documents\Plugins\Python\DiscordBot\Main.py", line 15, in <module>
    with open('config.json') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
``` can were help?
bright wedge
#

Define the path if file exists

slate swan
unkempt canyonBOT
#

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

!d discord.Member.display_avatar

unkempt canyonBOT
#

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

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

New in version 2.0.
shrewd apex
white citrus
#

is there an api with unlimited use that is free to use? she can also have a cooldown

bright wedge
forest oyster
#

hello, i have a problem with a simple command:
@bot.command()
async def server_info(ctx):
embed = discord.Embed(title=f"{ctx.guild.name}", description="Información del servidor:", timestamp=datetime.datetime.utcnow(), color=discord.Color.orange())
embed.add_field(name="Creación del servidor:", value=f"{ctx.guild.created_at}")
embed.add_field(name="Dueño del servidor", value=f"{ctx.guild.owner}")
embed.add_field(name="ID del servidor", value=f"{ctx.guild.id}")
embed.set_thumbnail(url=f"{ctx.guild.icon}")

await ctx.send(embed=embed)
#

the problem is in the last line

young dagger
#

I'm still receiving raise CursorNotFound errors logs. Do anyone know how to fix this problem? I'm using pymongo.

white citrus
#

is there an api with unlimited use that is free to use? she can also have a cooldown

unkempt canyonBOT
#

Hey @slate swan!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

young dagger
#

pymongo.errors.CursorNotFound: cursor id 3343587727049317749 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 3343587727049317749 not found', 'code': 43, 'codeName': 'CursorNotFound', '$clusterTime': {'clusterTime': Timestamp(1673983973, 3), 'signature': {'hash': b'}\r\x05o\xfejJ\x87!6\xf7?P\xa0\xb3\x00\xf7\xbf\x8fs', 'keyId': 7127295041399160841}}, 'operationTime': Timestamp(1673983973, 3)}

slate swan
#

no_cursor_timeout=True

white citrus
slate swan
white citrus
#

And they have unlimited uses?

white citrus
lament depotBOT
young dagger
# slate swan https://stackoverflow.com/questions/24199729/pymongo-errors-cursornotfound-curso...

So like this?

@tasks.loop(hours=24)
async def update_elo_ratings():
    # Get all the users in the collection
    cursor = collection.find(no_cursor_timeout=True)
    users = cursor
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(10)
    cursor.close()```
upbeat otter
upbeat otter
#

users = cursor

slate swan
young dagger
slate swan
lament depotBOT
upbeat otter
#

but ok

young dagger
upbeat otter
#

yes

young dagger
young dagger
# slate swan ✅ this should work

pymongo.errors.OperationFailure: noTimeout cursors are disallowed in this atlas tier, full error: {'ok': 0, 'errmsg': 'noTimeout cursors are disallowed in this atlas tier', 'code': 8000, 'codeName': 'AtlasError'}

#

Am I the only one with this issue?

white citrus
#

@slate swan is the google translate api also free and unlimited?

upbeat otter
upbeat otter
young dagger
upbeat otter
young dagger
#

And the error occurred

young dagger
shrewd fjord
#

;-;

upbeat otter
shrewd fjord
#

xd

upbeat otter
shrewd fjord
#

And make
no_timeout_cursot or something to False

#

no_cursor_timeout=False

upbeat otter
#

cursot UwU

shrewd fjord
young dagger
#

I heard motor is much better

upbeat otter
#

it's the same but just asynchronous

spiral crypt
#
async def kick(ctx, userName: discord.User, *, reason: str):
    await kick(user=userName, reason=reason)

I read thru the docs a bit and looked up some examples but i have 0 idea why this isnt working
/nvm im dumb i got it

sick birch
#

Unless you just left it off while pasting

spiral crypt
#

yeah i just left it out when copy pasting

@client.command()
async def kick(ctx, member: discord.Member, *, reason=None):
    await member.kick(reason=reason)

this ended up working

tough lance
young dagger
#

So I changed the code to:

@tasks.loop(hours=24)
async def update_elo_ratings():
    # Get all the users in the collection
    users = await collection.find().to_list(length=None)
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        await collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(10)```
#

@sick birch Do you think to_list() method can be used to retrieve the results of the find method as a list, instead of a cursor. and this should not give me any cursor errors anymore?

#

I'm using motor now btw

sick birch
scarlet aurora
#
        if message.channel == channel:
            if message.content in list:
                if mention == 'None':
                    msg = await echannel.send(f"``{message.author}`` wants to be promoted to ``{message.content}`` ``ini\n[Action Required!] Please reply with 'confirm' to accept this promotion``")
                else:
                    msg = await echannel.send(f"{mention} ``{message.author}`` wants to be promoted to ``{message.content}`` ``ini\n[Action Required!] Please reply with 'confirm' to accept this promotion``")

                def check(m):
                    return m.content == 'confirm' or m.content == 'Confirm' and m.reference and m.reference.message_id == msg.id

                message_id = payload.message_id
                if message_id == msg.id:
                    guild_id = payload.guild_id
                    guild = discord.utils.find(lambda g: g.id == guild_id, self.bot.guilds)

                    if str(payload.emoji) == "\U00002705":
                        role = discord.utils.get(guild.roles, name="[I] Member")

                        member = discord.utils.find(lambda m : m.id == payload.user_id, guild.members)
                        if member is not None:
                            await member.add_roles(role)
            

                        await self.bot.wait_for('message', check=check)
                        await echannel.send("Confirmed")```
#

Can someone help?

#

instead of replying to the message with confirm I'd rather do reaction tick or cross

slate swan
#

hey, i used to make discord bots a couple of months ago but i know the main library got discontinued or something so could someone please send an updated template thanks

sick birch
#

If that's what you mean by the "main library"

scarlet aurora
slate swan
#

oh really? I dont remember much but I remember the creator quitting

sick birch
#

It's still more or less the status quo

slate swan
#

well, has anything changed since i heard discord is getting rid of text commands

scarlet aurora
#

@sick birch

sick birch
#

I could recommend reading the migration guide

slate swan
#

@bot.slash_command(name="hi", guild_ids=[38292928])
async def command(inter: nextcord.Interaction):
await inter.response.send_message("hi")

glad cradle
#

disnake is better 😈

hushed galleon
sick birch
#

I personally would just recommend discord.py since your existing codebase may already be in discord.py. It also has the most support and maturity IMO

glad cradle
#

"maturity": the 2k kids making a discord Bot without knowing python

sick birch
#

I'm referring to the people who've been contributing for years

#

The one good / bad thing (depending on how you look at it) that came out Discord.py's toxic community is that it keeps most newcomers / inexperienced developers from contributing, lol

glad cradle
#

o_O Some things could be implemented in a better way (eg slash commands)

sick birch
#

Every library has its flaws

#

Though I personally haven't had any issues

#

I find it intuitive to work with

hushed galleon
#

so far ive been cool with the command tree and transformers

young dagger
#

ImportError: cannot import name 'ReturnDocument' from 'motor.core'

#

from motor.core import ReturnDocument

#

I installed motor with pip3 install motor, is there anything I'm missing?

hushed galleon
#

thats more of a #databases question but ReturnDocument appears to be part of pymongo, not motor itself

slate swan
#
  File "C:\Users\Name\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\Name\Desktop\PM-Beta\PM-Beta.py", line 131, in on_guild_channel_create
    euser = await audit_user(guild, discord.AuditLogAction.channel_create)
  File "c:\Users\Name\Desktop\PM-Beta\PM-Beta.py", line 34, in audit_user
    e = await guild.audit_logs(limit=1, action=action).get()
AttributeError: 'async_generator' object has no attribute 'get'```
young dagger
# hushed galleon thats more of a <#342318764227821568> question but ReturnDocument appears to be ...

Do you know how to fix this code using motor?

        # Increment the counter and use it as the case ID
        counter_doc = await counter_collection.find_one_and_update({"_id": "case_counter"}, {"$inc": {"count": 1}}, return_document=ReturnDocument.AFTER)
        if counter_doc is not None:
            case_id = counter_doc["count"]
        else:
            # No documents match the query, create a new document with a counter value of 1
            await counter_collection.insert_one({"_id": "case_counter", "count": 1})
            case_id = 1```
hushed galleon
young dagger
slate swan
#

thanks

hushed galleon
slate swan
#

can i still use prefix commands if my bot isnt in a 100 servers?

hushed galleon
#

below 100 servers you dont need to verify to enable message content, and any message that mentions the bot or goes to its DMs will receive message content regardless

young dagger
hushed galleon
#

go ask the motor devs that

slate swan
hushed galleon
#

if you dont enable the message content intent that is

slate swan
#

oh alright ill enable it

vocal viper
#

help me

hushed galleon
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

vocal viper
#

??

hushed galleon
#

Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

#

that tag is describing what intents are and how you'd add them to your bot constructor

#

also please make sure you've reset your token

vocal viper
#

okey

#

pls help me

hushed galleon
#

what part of the bot's tag are you confused about?

vocal viper
#

this problem

#

problemm

hushed galleon
#

unrelated topic, with the prevalence of embeds in bot and webhook messages, i have to wonder why discord still has a setting to disable embeds outright

hushed galleon
# vocal viper this problem

you need to specify what gateway intents your bot will be using when it connects to discord, as described by the tag

vocal viper
#

ok

#

thankss

slate swan
hushed galleon
# slate swan How?

well the link i sent describes it...

If you need to get next item from an iterator without a loop, you can use anext() (new in Python 3.10) or __anext__() instead:

# after
it = channel.history()
first = await anext(it)  # await it.__anext__() on Python<3.10
... ```
slate swan
#

why doesn't commands with ctx work for me?

hushed galleon
#

bot isnt running, bot cant see your message being sent, bot cant read the content of that message, bot isnt processing your message as a command, bot doesnt recognize the prefix of your command, bot doesnt recognize the command, etc.

we need to see your code, output, and what you've tried typing in discord to figure out what the issue is

steep totem
#

Hey! Is there maybe a way, to define a function, then make a lot of ifs and if one of the if is true, then set a variable to a specified number, thats in the function, and then run the function? It should probably look something like this, but sadly its not working.

def fankson(fanksonvariable):
    print(fanksonvariable)

@client.event
async def on_message(message, fanksonvariable):

    if message.author == client.user:
        return

    if message.content.startswith('$statsimportant'):
        fanksonvariable = 0
        if str(message.guild.id) == first_server_id:
            fanksonvariable = 1
            fankson()

        elif str(message.guild.id) == second_server_id:
            fanksonvariable = 2
            fankson()

        else:
            await message.channel.send("You don't have a license.")
hushed galleon
hushed galleon
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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

steep totem
slate swan
#
intents.message_content = True
``` this is still the old code i have changed it
hushed galleon
# steep totem wdym, can you please give me an example?
def get_stats_for(guild_id):
    ...  #        ^^^^^^^^ a function parameter

# in on_message:
guild_id = message.guild.id
if guild_id in licensed_guilds:
    stats = get_stats_for(guild_id)
    #                     ^^^^^^^^
    #       passes the value of the guild_id variable as a function argument```
hushed galleon
slate swan
#

the bot could read the message

steep totem
#

so not just check if its licensed or not, but check what is its unique 2-3word identifier

hushed galleon
slate swan
hushed galleon
#

an on_message prevents commands from running unless you explicitly tell your bot to process them

hushed galleon
#

do what the FAQ says, use bot.process_commands() or make it a listener

hushed galleon
slate swan
#

@client.command()
async def hello(ctx):
    await ctx.send("hello how are you?")
await client.process_commands(message)
#

So?

hushed galleon
#

it has to go inside your on_message event, and also match the same name you used in the @ decorator

#

you defined your Bot instance under the variable name client, and process_commands() is a method of Bot

slate swan
#

So whoever is @client above must also be a client below. being

steep totem
#

there are still a few unclear things in my head, but ill try 😊

steep totem
hushed galleon
steep totem
#

How can that be done, that i check for the guild id, if its = to a specified guild id by me, set a variable to a value set by the code, and then run a function with that variables inside.

#

I tried with ur code, but i still dont get how, and why it doesnt work... 😢

slate swan
#

will test it right away

young dagger
#

Should I close the connection to the database after it updated all users?

@tasks.loop(hours=24)
async def update_elo_ratings():
    # Get all the users in the collection
    users = await collection.find().to_list(length=None)
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        await collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(10)```
hushed galleon
#

so if you want it to have a certain value, call the function with that value and the parameter will have that value inside the function

steep totem
#

oh now i get it

#

omg

#

thank you 🥰

hushed galleon
young dagger
#

I'm using motor and this code. I don't want to keep an I/O operation open for a long time. It should close the connection after it's done updating all the users. Do I have to include some extra codes to do that? @hushed galleon

hushed galleon
#

if you open the connection inside your loop, then you shouldnt have to worry about any side effects when closing it afterwards

young dagger
young dagger
# hushed galleon if you open the connection inside your loop, then you shouldnt have to worry abo...

Let me explain what I mean. So yesterday I received this kind of error.

pymongo.errors.CursorNotFound: cursor id 3343587727049317749 not found, full error: {'ok': 0.0, 'errmsg': 'cursor id 3343587727049317749 not found', 'code': 43, 'codeName': 'CursorNotFound', '$clusterTime': {'clusterTime': Timestamp(1673983973, 3), 'signature': {'hash': b'}\r\x05o\xfejJ\x87!6\xf7?P\xa0\xb3\x00\xf7\xbf\x8fs', 'keyId': 7127295041399160841}}, 'operationTime': Timestamp(1673983973, 3)}```
slate swan
#

@hushed galleon the hello command works but if someone leaves the server there is no message

young dagger
#

@sick birch told me: users was probably some sort of cursor object, when it was not closed, you were keeping an I/O operation open for a long time

#

So I changed to motor. And I don't want the same thing happened again.

sick birch
#

Motor probably provides an async ctx manager to handle closing for you

#

You'd have to refer to docs as this is becoming #databases

slate swan
young dagger
# sick birch Motor probably provides an async ctx manager to handle closing for you

With that being said. Is there anything I have to change to my code to use an async ctx manger? Here is the code once again:

@tasks.loop(hours=24)
async def update_elo_ratings():
    # Get all the users in the collection
    users = await collection.find().to_list(length=None)
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier, rank = get_tier_and_rank(summoner_name, summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        await collection.update_one({"summoner_id": summoner_id}, {"$set": {"tier": tier, "rank": rank, "elo_rating": elo_rating}})
        await asyncio.sleep(10)```
sick birch
#

Not sure
Never used motor
I would check their documentation

hushed galleon
slate swan
#

no idea

pliant gulch
pliant gulch
slate swan
#

Windows

pliant gulch
#

What version of aiohttp?

slate swan
#

Aiohttp?

hushed galleon
#

i would doubt that would be the issue if the bot was working earlier, but tbf i havent seen an error like that before

pliant gulch
#

That error is related to DNS

#

So something is wrong with the DNS

#

As far as I can see

young dagger
#

Do you guys use an async ctx manger?

#

I mean when you are updating information about users etc

vale wing
winged linden
#

How would I make a giveaway end command?

rare echo
winged linden
rare echo
#

then clear reactions if ya want

winged linden
#

Okay

#

how do i clear reactions

rare echo
#

i want to say just get the reaction then reaction.remove

#

but ill have to double check that for ya in a sec

winged linden
#

ok

rare echo
#

quick search just says you can do the whole message with clear_reaction() on the message obj

#

!d discord.Message.clear_reactions

unkempt canyonBOT
#

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

Removes all the reactions from the message.

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

there you go

fair magnet
#

could anyone tell me at which part of the docs i have exactly to look for dc bot sending dm as response from a command

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

Sends a message to the destination with the content given.

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

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

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

Hello! odd question but, ive been trying to figure out how to integrate this one module into my discord bot for the last few hours and quite honestly i have nothing to show for it, i keep hitting a wall and was wondering if anyone could help me out? https://pychievements.readthedocs.io/en/latest/ is the module in question

young dagger
#

@sick birch So far, I have not encountered any Cursor errors with motor, even when not using the 'close' function.

slate swan
#

My clickable title isn't working

#

I did [Text Here](Link Here)

young dagger
#

What is the way to handle and ignore errors like 'discord.ext.commands.errors.CommandNotFound: Command "customgames" is not found' ?

slate swan
#
@bot.slash_command(description="Change the bots pfp")
@application_checks.has_permissions(administrator=True)
async def change_pfp(interaction: nextcord.Interaction, avatar:nextcord.Attachment):
    with open(avatar, 'rb') as image:
        await bot.user.edit(avatar=image)``` this is my code and im trying to make a command that will change my bots pfp, this is the error im getting ```TypeError: expected str, bytes or os.PathLike object, not Attachment

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

nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: expected str, bytes or os.PathLike object, not Attachment```. anyone know a fix
primal token
#

You need to use this iirc

#

!d discord.Embed.url

unkempt canyonBOT
primal token
unkempt canyonBOT
#

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

Retrieves the content of this attachment as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.11)") object.

New in version 1.1.
slate swan
#

so do i replace the bot.user.edit with that??

slate swan
#

or where do i add that at

sick birch
#

Long I/O waits are not a problem for async

primal token
sick birch
#

Wastes resources at worst

slate swan
primal token
#

You would pass it to await bot.user.edit(avatar=image)?

#

So you would just do

await bot.user.edit(avatar=await avatar.read())
slate swan
#

ok

slate swan
primal token
#

dont open it

slate swan
#

ok

primal token
#

Remove the first line after the function definition

slate swan
#

alr i got it

primal token
#

Yep! btw add a space after the word avatar in the parameters

slate swan
#

Nvm i did it

young dagger
#

What is the optimal way to handle CommandNotFound error?

young dagger
# sick birch Ignore it

Good way to ignore it?

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        pass
    else:
        raise error```
sick birch
#

Bots that say "did you mean X" when you type the wrong command are annoying

sick birch
#

I would let it log just for logging purposes but other than that just ignore it

young dagger
#

Ok

slate swan
#

how can i make a command so that when someone authorizes with my bot and They allow the bot to join servers for them, and if they leave the server i can run a command that will pull them back in

#

asking for a friend

sick birch
slate swan
sick birch
#

There have been these bots going around recently that force users to stay in a server against their will

slate swan
#

thats not what im trying to do so can someone help

sick birch
#

That seems to be exactly what it is
Why do you want to pull a user back into a server if they leave?

#

That seems to go against the intention of "leaving" a server

#

I would take a look at Discord's Developer Terms of Service Section 2b.

slate swan
sick birch
#

You can DM them the invite instead

#

!d discord.Member.send

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

Sends a message to the destination with the content given.

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

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

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

Even then is... questionable. You're DMing a user that is no longer in your server

slate swan
#

yeah thats why i want my method

sick birch
#

The other method is even more questionable and certain violates Discord's developer policy and terms

#

Just send them an invite to your server. It'll most likely fail since they no longer share a server with your bot, though so that makes it much better

slate swan
#

but if i cant invite them because they have me blocked

#

but they dm my friend saying they want to join and he cant make invites

sick birch
#

That is the user's choice and in accordance with the developer policy

#

If they have the setting enabled, that means they do not want to be contacted from bots that are in their server and you have to respect that

sick birch
#

Create some other avenue for them to contact you for an invitation link

#

Forcing all users to stay in a server just for a few users that do actually want to rejoin is against Discord's policies

static epoch
sick birch
# slate swan no just that user

If it's just one user it shouldn't be a big deal to give them your Discord contact information if they need to rejoin back

#

Why waste the time and effort creating a whole Oauth application process just for one user?

#

Just add them as a friend and they can DM you whenever for an invite 😄

hollow gazelle
#

bot = discord.Bot(command_prefix='!', activity=activity, status=discord.Status.online)
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

torn sail
hollow gazelle
#

Traceback (most recent call last):
File "C:\Users\rhino\OneDrive\Desktop\Xenon Order bot\main.py", line 21, in <module>
intents.message_content = True
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Intents' object has no attribute 'message_content'

hollow gazelle
#

let me check

torn sail
#

pip uninstall discord, pip uninstall discord.py, pip install discord.py

slate swan
#

I wanted to create a command where the bot designates roles to a certain user upon mention

eg. c-role @user
the role ids/roles will already be defined in the code

#

does anyone know how to do this?

#
import logging
import discord
from discord.ext import commands

logging = logging.getLogger('Discord')
print ("loading...")

spooky = commands.Bot(
    command_prefix="c-",
    intents=discord.Intents.all(),
    case_insensitive = True,
    help_command=None,
    )

@spooky.event
async def on_ready(server):  
    print("Hello World!")

@spooky.event
async def on_ready():

    if .guild.id != 1063661449832058961:
        return
    log_channel = spooky.get_channel(958975903839428668)
    mm_role1 = .guild.get_role(1063671567046946897) 
    mm_role2 = .guild.get_role(1063699294227537940)

    @spooky.command()
    async def mm(ctx, member : discord.Member):
        await member.add_roles(mm_role1, mm_role2)```
#

this is kinda what I've done so far, I want it to be so the bot recognises the server id and then the command c-mm @user will add certain roles but I'm kind of stuck

lone lichen
#

In on ready you dont have guild defined

tough lance
#

Also why do you have two on_ready events anyway?

sick birch
#

You most likely do not even need the 2nd on_ready

#
@spooky.command()
async def mm(ctx, member: discord.Member):
  ...

is good enough

slate swan
#

okay! thank you,!

slate swan
lone lichen
#

!d discord.Guild.roles

unkempt canyonBOT
#

property roles```
Returns a sequence of the guild’s roles in hierarchy order.

The first element of this sequence will be the lowest role in the hierarchy.
lone lichen
#

This?

slate swan
#

yes, thank you!

lone lichen
#

Also when you define mm_role1 It’ s only accessible inside that on_ready function and not in the command

slate swan
#

I see, I've updated my code to this:

#
import logging
import discord
from discord.ext import commands

logging = logging.getLogger('Discord')
print ("loading...")

spooky = commands.Bot(
    command_prefix="c-",
    intents=discord.Intents.all(),
    case_insensitive = True,
    help_command=None,
    )

@spooky.event
async def on_ready():  
    print("Hello World!")

log_channel = spooky.get_channel(958975903839428668)
mm_role1 = discord.guild.Role(1063671567046946897) 
mm_role2 = discord.guild.Role(1063699294227537940)

@spooky.command()
async def mm(ctx, member: discord.Member):
  await member.add_roles(mm_role1, mm_role2)```
#

but it gives me an error whenever I run it

lone lichen
#

What error

slate swan
#

Traceback (most recent call last):
File "/Users/myname/Custom bot/main.py", line 20, in <module>
mm_role1 = discord.guild.Role(1063671567046946897)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Role.init() takes 1 positional argument but 2 were given

lone lichen
#

!d discord.Guild.get_role

unkempt canyonBOT
#

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

Changed in version 2.0: `role_id` parameter is now positional-only.
lone lichen
#

Also you dont use discord.Guild class

#

U need an instance of that class which represents a specific guild

slate swan
lone lichen
slate swan
#

thanks !

real badger
#

Can someone help:
discord.app_commands.errors.CommandInvokeError: Command 'review' raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'reviews.json'

naive briar
#

Read the error

real badger
#

I figured it out

#

Is there a way to do an Integer-only input in a modal?

slate swan
#

Does anyone know how to add a dynamic timestamps to embeds?

naive briar
unkempt canyonBOT
#

discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.

This allows for a locale-independent way of presenting data using Discord specific Markdown...
slate swan
#

thanks!

slate swan
naive briar
#

Just ask it

slate swan
# naive briar Just ask it
 middleman.add_field(
     name="Date added:",
     value=f"{datetime.utcnow}",
     inline=True
  )
  await ctx.send(embed=embed)```
#

code at start:

discord.utils.format_dt(datetime.utcnow(), style="R")```
sick birch
#

It's not an in-place operation

slate swan
#

I'm trying to make it display in this format:

eg. Date added: 5 years ago (constantly changing as time changes) but it displays like this instead

sick birch
#
dynamic_timestamp = discord.utils.format_dt(...)
my_embed.add_field(..., value=dynamic_timestamp)
slate swan
sick birch
#

Yes

slate swan
#

got it, thanks!

slate swan
# sick birch Yes

it displays as a dynamic timestamp now, but rather than it constantly changing as time changes, it simply just says "11 hours ago"

#
dynamic_timestamp = discord.utils.format_dt(datetime.utcnow(), style="R")
  embed=discord.Embed(
     title="⠀⠀ User Added﹕ ✦", 
     description=f"{member.mention} is now a <@&1063671567046946897>", 
     color=discord.Color(0x7896a1)
    )
  embed.set_thumbnail(url=member.avatar)
  embed.add_field(
     name="Added by:",
     value=f"{ctx.author.mention}"
  )
  embed.add_field(
     name="Date added:",
     value=dynamic_timestamp,
     inline=True
  )
  await ctx.send(embed=embed)```
sick birch
torn sail
#

is there a limit to the amount of rows in a view?

slate swan
sick birch
torn sail
#

thanks

sick birch
slate swan
#

okay!

sick birch
#

You're probably UTC - 11 I'm assuming

slate swan
#

yeah

ionic garden
#

how do i take an argument as a list of users

torn sail
unkempt canyonBOT
#

class discord.ext.commands.Greedy```
A special converter that greedily consumes arguments until it can’t. As a consequence of this behaviour, most input errors are silently discarded, since it is used as an indicator of when to stop parsing.

When a parser error is met the greedy converter stops converting, undoes the internal string parsing routine, and continues parsing regularly.

For example, in the following code:

```py
@commands.command()
async def test(ctx, numbers: Greedy[int], reason: str):
    await ctx.send("numbers: {}, reason: {}".format(numbers, reason))
```  An invocation of `[p]test 1 2 3 4 5 6 hello` would pass `numbers` with `[1, 2, 3, 4, 5, 6]` and `reason` with `hello`...
torn sail
#

membesr: commands.Greedy[discord.Member]

earnest pike
#

use variadic if its at the end of the parameter

torn sail
#

yep *members: discord.member

slate swan
#

does anyone know how to program so that after "who are you adding?" the bot will recognize the person being roled by either mention or discord id?

#
@spooky.command()
async def add(ctx):
    await ctx.send("Lets start! Who are you adding?")
    button1 = Button(label="role", style=discord.ButtonStyle.blurple)
    button2 = Button(label="role", style=discord.ButtonStyle.red)
    button3 = Button(label="role", style=discord.ButtonStyle.green)
    button4 = Button(label="role", style=discord.ButtonStyle.blurple)
    button5 = Button(label="role", style=discord.ButtonStyle.blurple)

    async def button1_callback(interaction):
        await interaction.response.edit_message(content="**Adding as role!**", view=None)

        view = View()
        view.add_item(button4)
        view.add_item(button5)
        await ctx.send("What games can they do?", view=view)
        
        async def button5_callback(interaction):
            await ctx.send("role added!")

        button5.callback = button5_callback

    
    button1.callback = button1_callback

    view = View()
    view.add_item(button1)
    view.add_item(button2)
    view.add_item(button3)
    await ctx.send("What role will they receive?", view=view)```
#

and before sending the response "What role will they receive?"

sick birch
#

So if you're 100% sure you're up for it I can tell you

#

Otherwise best to rethink

slate swan
#

sorry If I'm a bit slow or ask questions though 😭

sick birch
#

!d discord.ext.commands.RoleConverter.convert

unkempt canyonBOT
#

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

The method to override to do conversion logic.

If an error is found while converting, it is recommended to raise a [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError") derived exception as it will properly propagate to the error handlers.
slate swan
sick birch
#

I would prefer we keep things here

#

But you basically using the RoleConverter to parse a Role

#

BTW this is what discord.py uses under the hood when you do : discord.Role

#

If it's inside an interaction you may have to construct a mock context from interaction

slate swan
#

are you able to give me an example of what it would look like in my code? Im still really confused

it's supposed to work like the bot asks a question > the member gets pinged/id is sent and bot recognizes that as the person they are going to be adding or removing roles from

terse coyote
#

how to do code like this:

def shared_cooldown(rate, per, type=BucketType.default):
    cooldown = Cooldown(rate, per, type=type)
    def decorator(func):
        if isinstance(func, Command):
            func._buckets = CooldownMapping(cooldown)
        else:
            func.__commands_cooldown__ = cooldown
        return func
    return decorator

but for app_commands?

vale wing
#

!d discord.app_commands.checks.cooldown

unkempt canyonBOT
#

@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.

The `key` function can optionally be a coroutine.

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.

Examples

Setting a one per 5 seconds per member cooldown on a command:
vale wing
#

@terse coyote ^ just a simple decorator

severe mural
#
    ^
IndentationError: expected an indented block
``` uhh error...

here code:
```@client.event
async def on_guild_join(guild):
 print(f'Bot has been added to a new server: {guild.name}')
 print('List of servers the bot is in: ')
 for guilds in bot.guilds:
    print(guilds.name)```
#

AH

#

Hmm werid

shell wing
#

why are my commands not working when my event is ?

slate swan
#

^ , or the event is blocking

shell wing
# vocal snow https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-...
@bot.event
async def on_message(message):
  if message.channel.id == 1060675394585505904 and not message.author.id == bot.application_id: #use ur channel id
    try:
        headers = {"Authorization": api_key}
        params = {"user_id": message.author.id, "message": message.content}
        async with aiohttp.ClientSession(headers=headers) as session:
            async with session.get("https://v6.rsa-api.xyz/ai/response", params=params) as resp:
                json_response = await resp.json()
                message1 = json_response["message"]
                msg = await message.reply(message1)
    except Exception as e:
      msg = await message.reply(e)
    await bot.process_commands(message)
``` have this still doesnt work
vocal snow
#

look where you're processing commands

shell wing
#

auto indents fked up

vocal snow
#

(inside the if statement)

sweet ore
#

How to shutdown the bot?

#

instead of killing the Terminal

vale wing
#

Loop should close gracefully

#

Depends from where you wanna do that

loud junco
#

i cant define bot with a function
but i can define bot with class, but __init__ cant be async

#

anyone has any clue on how to work it out?
i did some research on OOP but still has no clue

severe mural
#

Found solution

#

sigh.

loud junco
#

huh

vale wing
unkempt canyonBOT
#

await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.
loud junco
vale wing
#

You use this in a Cog subclass

vale wing
loud junco
vale wing
#

Test*

#

test1() is a method

loud junco
#

i thought Test is the class?

vale wing
#

Yes

#

Why can't class be a subclass lol

#

Your OOP knowledge is probably not well organised, I advise to take additional course to settle things

loud junco
#

💀 ok

loud junco
slate swan
#

corey's yt tutorial

vale wing
#

I can't recommend any concrete ones, but you can search on resources like udemy, stepik and !resources

#

Hey sarth

slate swan
#

yo👋

loud junco
#

wait u are sarth?

#

oof

slate swan
#

yeah

loud junco
#

been screwing my bot for 1 year and its still ded

vale wing
#

We're currently making bobux bot

#

We have await is_stupid(...), BadModal, Girlfriend.AMONGUS and other cool stuff

vale wing
#

And yeah we have whole user_insults.json

loud junco
vale wing
#

There are 5 of us

slate swan
#

maybe not directly related to discord bots (but i want my bot to send the image) , but my images from this hosting service are not embedding into discord. what may be the reason and can i fix it?

https://live.staticflickr.com/65535/48378381527_aa3c6a39a4_o.png

sweet ore
#

I am being rate limited with discord's api

slate swan
#

stop using replit

sweet ore
#

Testing the bot

slate swan
#

then you're making too many requests to the api

sweet ore
severe mural
#

@vale wing Hello little help sorry explain:

#

there "why" same list server , list server... is bad example "list server: hola server, como server , etc"

code:

        embed.add_field(name="List Server", value=f"{guilds.name}")```
vocal snow
#

why are you adding a field for each guild then

severe mural
#

how field idea example:

List Server:
Hello server
como server...

vocal snow
#

you should make a string with the guild names; ```py
", ".join(g.name for g in client.guilds)

severe mural
#

sorry is python lol.

#

okay sigh.

#

hmm moment think,,,

severe mural
#

i see found search google

slate swan
severe mural
#

maybe is "value=self.create_list(top_users, [f'<@{user}>' for _, user in top_users]),"

#

idk.

slate swan
severe mural
slate swan
severe mural
slate swan
#

embed.add_field(name="List Server", value=(guilds.name for guilds in client.guilds))

severe mural
#

i see think remove ","

slate swan
slate swan
severe mural
#

but i am little .

slate swan
severe mural
sweet ore
slate swan
#

But yea your learning

sweet ore
slate swan
sweet ore
#

i will fix it

severe mural
#

hmm think no solution lol.

slate swan
vale wing
severe mural
#

(yeah is client.event)

#

"client = commands.Bot(command_prefix="&", intents=intents)"

vale wing
#

@severe mural can you please explain what exactly your problem is? If you are struggling to talk in English just use translator (you speak spanish right?)

vale wing
severe mural
severe mural
vale wing
#

Just put server name to field name and server description to field value

vale wing
#
for guild in guilds:
    embed.add_field(name=guild.name, value=guild.description, inline=False)```
#

Dunno if in dpy they've kword only

#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining. Can only be up to 25 fields.
severe mural
#

i see.

vale wing
#

Too bad

severe mural
#

maybe is example: Value to description.

vale wing
#

In disnake everything's better

severe mural
#

XD

#

okay i see..

vale wing
#

!d disnake.Embed.add_field

unkempt canyonBOT
#

add_field(name, value, *, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining.
vale wing
#

Yeah love them being positional

shrewd apex
#

out of habit i still use kwarg

vale wing
severe mural
#

yeah moment check think complicated.

#

ah guilds.description do not exist.

#

or yes, maybe but error " expected an indented block"

vale wing
severe mural
vale wing
#

!d discord.Guild.description

unkempt canyonBOT
vale wing
vale wing
slate swan
vale wing
#

Nextcord has best modals you say?

severe mural
#

future nextcord xd

severe mural
slate swan
severe mural
#

but think.. sigh.

slate swan
#

I've used them multiple times flawless

vale wing
#

Idk seem similar to disnake ones except they assign them as attributes

slate swan
vale wing
#

Yeah I just seen that

#

We have the superior modal in bobux bot

slate swan
severe mural
#

Okay, no problem @vale wing

#

thanks and tomorrow question other help expert.

vale wing
slate swan
vale wing
#

I am da manager

#

And the modal is so good

slate swan
#

Ngl nextcord modals solo

vale wing
#
modal = Modal(...)
results, m_inter = await modal.wait()```
slate swan
#

Nextcord cleaner don't lie

severe mural
#

there last is list server

slate swan
#

listGuild = []
for guild in client.guilds:
listGuild.extend(guild.name)

#

Then all you do is use listGuild variable in value

severe mural
#

Hmmm

severe mural
#

example "value=(listGuild))"

#

lol.

#

maybe

#

@slate swan wtf

vale wing
# slate swan ewwww

Imho having consequential parts of code in different places is bad code design and all libraries actually do that for some reason

shrewd fjord
slate swan
shrewd fjord
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the guild’s audit logs.

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

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
shrewd fjord
slate swan
#

Error:


AttributeError: 'async_generator' object has no attribute 'get'```
slate swan
upbeat gust
slate swan
upbeat gust
#

Why not

slate swan
#

await audit_ch(guild, discord.AuditLogAction.role_create)

upbeat gust
#

And why not just use anext like the other person suggested if you don't want to do an async for loop

slate swan
upbeat gust
#

what

vale wing
#

That is a thing right

upbeat gust
#

No

#

That's outdated

vale wing
#

When was it outdated

slate swan
upbeat gust
#

I'm not talking to you

upbeat gust
upbeat gust
vale wing
#

A they switched to a builitin async gen

#

That doesn't have that method obviously

vale wing
#

Or that's not builtin

slate swan
vale wing
#

Screw them I am disnake user

slate swan
#

:/

upbeat gust
slate swan
upbeat gust
#

literally like 3 people have answered

#

Consider actually reading the messages people send.

slate swan
upbeat gust
upbeat gust
#

Like 4 different ways you could do it

slate swan
upbeat gust
#

so have you read it?

slate swan
slate swan
upbeat gust
slate swan
#

Yes

#

Thk

upbeat gust
# slate swan No

I highly recommend at least knowing some python before trying to make a bot

slate swan
#

Working

#

I'm sorry I just misunderstood

slate swan
slate swan
#
bot.load_extension(f'cogs.{file[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
shrewd fjord
#

"await" uwu

#

await it

slate swan
loud junco
#

but really learn english before learning python

#

everything is going to be clear after that

#

or memorise the meaning of certain term in python

dapper cobalt
slate swan
#

But the code worked on another PC

slate swan
shrewd fjord
naive briar
slate swan
#

cog loading is now async

slate swan
#

Why can't I use "@bot.command()"? Could this be because I used a bunch of "@bot.event"?

slate swan
slate swan
slate swan
#

@bot.command()*

#

Sorry

#

!intents you need message_content intents for that to work

unkempt canyonBOT
#

Using intents in discord.py

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

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

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

from discord import Intents
from discord.ext import commands

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

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

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

slate swan
#

My code:

async def test(ctx):
    await ctx.send("Text")```
#

Bot ignores

#

...

slate swan
#

your code will not work without that intent.

#

atleast read what the embed says

slate swan
#

the code for commamd should be above bot.run

slate swan
#
async def test(ctx):
    await ctx.send("Text")

bot.run(token)```
#

can you show your full code

#

!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

slate swan
#

can show base?

elder venture
#

Heyoo, just a quick question:
Im coding a Bot thats checking Ports. Its working. Now i want it to loop every minute but i dont want to use the .sleep function because its blocking ressources (am i right there?).
Is it smarter to use a scheduler then or is ther a better way to solve that problem?

slate swan
slate swan
# slate swan can you show your full code
from discord.ext import commands
import json

color_1 = 192
color_2 = 192
color_3 = 192

default_whitelist = [

]

black_list_bots = [

]

with open(r"cong.json") as f:
    j = json.load(f)
    token = j["token"]
    prefix = j["prefix"]

intents = discord.Intents.default()
intents=discord.Intents.all()

bot = commands.Bot(command_prefix="pm.", intents=intents)
bot.remove_command('help')

#Code "@bot.event"...

@bot.command()
async def test(ctx):
    await ctx.send("Text")

bot.run(token)```
#

do you have an on_message event

slate swan
#

if yes, change .event on it to .listen()

#

with the brackets

slate swan
slate swan
unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Example of coroutine displaying the current date every second for 5 seconds:
slate swan
#

but a task would be a much better option

#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
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 "discord.ext.tasks.Loop").
slate swan
elder venture
slate swan
#

What's code for command deleting

#

Like when i say !down it sends respond but deletes my message

#

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

slate swan
#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").

Changed in version 1.1: Added the new `delay` keyword-only parameter.
ebon island
#

How does one get the current track time / position for a playing mp3 in dpy/disnake?

#

does it require something jank like incrementing time since the start via cron or something and pausing on pause or something? That sounds awful, it'd be really cool if dpy/disnake just knows and can yield that info

tough lance
#

Hi, I don't have much experience with logging module, but just setting up logging for disnake with a file loaded that file with 56 mb of stuff

slate swan
#

are you logging debugs too?

tough lance
#

Yes

slate swan
#

it should be 56mb either way, unless you have tons of dependencies

slate swan
#

the sole task is sending packets

#

read your voice server's docs to find out

teal glade
#

I want to create toggleable chat filters for my bot. Basically it replaces a member's message with a completely different string when turned on...

#

Is it possible to edit another user's message with discord.py?

slate swan
#

no

#

trying to setup custom context, getting discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'approve'

am i doing this wrong or something

async def approve(self, *args, value: str, **kwargs) -> discord.Embed:
        return discord.Embed(description=f"{self.author.mention} {value}", color=discord.Color.green())```

```py
from objects.context import Context


    @commands.command()
    async def ping(self, ctx: Context):
        await ctx.approve(value=f"Pong! {round(self.bot.latency * 1000)}ms")```
maiden fable
teal glade
# slate swan no

What if I want to create a webhook for the channel and send a translated message using it?

slate swan
teal glade
#

Okay, so how can I create one to mimic a user's profile (display name and avatar)?

#

I never done webhooks with the API

slate swan
#

!d discord.TextChannel.create_webhook

unkempt canyonBOT
#

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

Creates a webhook for this channel.

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

Changed in version 1.1: Added the `reason` keyword-only parameter.
slate swan
#

it has the arguments you need

shrewd fjord
#

Yo

teal glade
#

I have made this event so that if a member id is saved inside the 'muffled' list, the member's message will be replaced with a webhook with the same display name and avatar that says the "muffled" text

@client.event
async def on_message(message):
    if message.author.id in muffled:
        webhook = await message.channel.create_webhook(name="Themis Message Filter", avatar=message.author.display_avatar)
        await webhook.send(textmuffle(message.content))
shrewd fjord
#

So what's the prob?

#

It's working, u just need to delete the author's message

teal glade
#

I get an AttributeError

slate swan
#

Attribute error to?

teal glade
#
Traceback (most recent call last):
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\kiranira\Desktop\Coding\discord.py\themis\main.py", line 18, in on_message
    webhook = await message.channel.create_webhook(name="Themis Message Filter", avatar=message.author.display_avatar)
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\channel.py", line 587, in create_webhook
    avatar = utils._bytes_to_base64_data(avatar)  # type: ignore # Silence reassignment error
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 612, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 598, in _get_mime_type_for_image
    if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
AttributeError: 'Asset' object has no attribute 'startswith'
slate swan
#

it takes a string ( the url)

teal glade
#

ASfacepalm thanks

shrewd fjord
#

It returns asset obj :0

slate swan
#

is it possible to run 2 bots in one project ?

shrewd fjord
#

Running diff file from each terminal, yes

slate swan
unkempt canyonBOT
#

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

spooky
shrewd fjord
#

:0

slate swan
# shrewd fjord Running diff file from each terminal, yes

i mean this

from discord.ext import commands

client = commands.Bot(command_prefix="!")
bot = commands.Bot(command_prefix=".")

@client.event
async def on_ready():
    print('The bot is ready')

@bot.event
async def on_ready():
    print('The bot is ready')


@bot.command()
async def copy(ctx,server:discord.Guild):
    await ctx.reply("**Copying...**")
    guild = client.get_guild(server.id)
    new_guild = await client.create_guild(name=guild.name, icon=guild.icon)
    print("eheh")

client.run("token")
bot.run('token')```
shrewd fjord
#

Breh

vale wing
#

Bro just create 2 several bots

shrewd fjord
#

Weird stuff

slate swan
slate swan
vale wing
#

If you need interprocess communication embed API

slate swan
slate swan
vale wing
#

Or whatever websocket on local machine

slate swan
#

create a simple api or database integration to connect the bots

vale wing
#

Seems legit

teal glade
shrewd fjord
#

Full traceback

vale wing
#

!d discord.Asset.url

unkempt canyonBOT
vale wing
#

Weird it's not bytes

shrewd fjord
#

:0

vale wing
#

How do you use startswith and on what

teal glade
# shrewd fjord Full traceback
Traceback (most recent call last):
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\kiranira\Desktop\Coding\discord.py\themis\main.py", line 18, in on_message
    webhook = await message.channel.create_webhook(name="Themis Message Filter", avatar=message.author.display_avatar.url)
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\channel.py", line 587, in create_webhook
    avatar = utils._bytes_to_base64_data(avatar)  # type: ignore # Silence reassignment error
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 612, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
  File "C:\Users\kiranira\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\utils.py", line 598, in _get_mime_type_for_image
    if data.startswith(b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A'):
TypeError: startswith first arg must be str or a tuple of str, not bytes```
vale wing
#

What is data and how do you get it

#

And why the heck do you check for a literal bytestring

#

A wait that's internal

teal glade
shrewd fjord
#

Yea

vale wing
#

Eh wait lemme check docs

#

!d discord.TextChannel.create_webhook

unkempt canyonBOT
#

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

Creates a webhook for this channel.

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

Changed in version 1.1: Added the `reason` keyword-only parameter.
vale wing
#

@teal glade avatar=await user.display_avatar.read()

teal glade
#

message.author?

vale wing
#

Idk what is your user

vale wing
#

If you know OOP you got what I meant

teal glade
#

ah okay

#

Well it made the webhook

terse coyote
vale wing
#

Next command globally?

teal glade
dusky ravine
#

hey, i'm trying to run a python bot for discord, but the on_message function isnt working

#
import discord
import mysql.connector

client = discord.Client(intents=discord.Intents.all())

TOKEN = 'your_bot_token'
CHANNEL_ID = 'your_channel_id'

cnx = mysql.connector.connect(
    host="your_host",
    user="your_user",
    password="your_password",
    database="your_database"
)

@client.event
async def on_message(message):
    if message.content.startswith("!register") and message.channel.id == CHANNEL_ID:
        accountname = message.content.split(" ")[1]
        discordid = message.author.id
        cursor = cnx.cursor()
        query = f"UPDATE account SET reg_mail = '{discordid}' WHERE username LIKE '%{accountname}%'"
        cursor.execute(query)
        cnx.commit()
        cursor.close()
        await message.channel.send(f"{accountname}'s account has been updated successfully!")

client.run(TOKEN)
#

when I try the !register command in the designated channel nothing happens