#discord-bots

1 messages · Page 280 of 1

sick coyote
#

but the other problem is i made a whole dashboard.

vale wing
#

Tbh if lots of time passed since you created that code and your code style and stack got better I would recommend simply rewriting it from the beginning no matter how big the bot is

keen trail
sick coyote
#

becuase i dont wanna rewrite anything in that bot

vale wing
#

Dashboard interacts with bot through db I assume

sick coyote
#

yeah

#

i made the dashboard for every category

vale wing
#

So it's not a problem

sick coyote
#

and to just throw it away idk.

sick coyote
keen trail
#

i finnaly can talk about favorite coding language without getting warned

sick coyote
#

nice

keen trail
#

js coding ugh

#

or lua

#

ughhh

vale wing
sick coyote
#

idk what im gonna do

keen trail
keen trail
sick coyote
#

why does discord even invent a new intent

keen trail
#

life is problem so every human have problem

keen trail
vale wing
#

Adapting text commands to slash is so painful you would better just implement same functionality from scratch

keen trail
#

though there is only 3

sick coyote
#

but its not as old as the others

keen trail
sick coyote
#

the easiest way to solve it if i get message content intents

#

everything will be perfect

vale wing
#

Or just scam discord for mc intent heheheha_c

keen trail
#

but discord is dum and thinks i got slash command script connected and gives slashcommand badge to my bot

sick coyote
sick coyote
#

if i rewrite my bot im gonna do it like anti nuke based or something like that

keen trail
#

its painful

sick coyote
#

yeah

slate swan
#

i always wondered what that all anti nuke bots do

keen trail
#

currently make typos deletion and fix them from list and made bot understand even 1 year old kids responses

vale wing
keen trail
#

kick everyone

#

thats what they do

sick coyote
#

hmmmmmm

slate swan
keen trail
#

nuke is dump whole server and users dm

vale wing
#

My AIAS bot deletes people for sending more than 4 periods in a row.....

keen trail
#

got 4k pings from each server

vale wing
#

Although it's still better than discord antispam

slate swan
keen trail
#

hm if bot would have perms to edit users messages

slate swan
#

spam @everyone and delete channels, ban members etc

vale wing
#

Nuke is that thing that does big boom

keen trail
#

it makes millions of pings

slate swan
#

just destroy server lol

vale wing
#

Boom boom get outta my room or smth

slate swan
#

but how you wanna stop that using a bot

sick coyote
#

do you have any idea what bot i should do

keen trail
slate swan
sick coyote
vale wing
#

Think of 3 ideas, ignore them all, pick 4th

sick coyote
#

i made a custom bot for a server

vale wing
#

Oh no bobux unknown exception alert cya guys

keen trail
#

i made a feature for my bot that is crazy secure

slate swan
keen trail
#

u need a card to get perms

vale wing
#

Nvm it's interactiontimedout

#

Nothing serious

keen trail
#

for real admin dont scan and dont have perms

slate swan
vale wing
#

Yus

sick coyote
#

wadafak

vale wing
#

Hate this thing

slate swan
#

Traceback

vale wing
#

k

#

most recent call last btw

slate swan
#

worst part about discord libraries errors is that its doubled

#

cause there is always CommandInvokeError

vale wing
#

Yeah screw them

keen trail
#

not having errors

slate swan
#

like its the same thing skull

harsh orbit
#

How I can make the command deleted when it typed?

sick coyote
vale wing
#

await ctx.message.delete()

keen trail
#

the only one problems i got with discord bot that dont have space on disl

#

disk

vale wing
keen trail
#

bc node gr3 on hosting is full

vale wing
#

Actually depends on bot

keen trail
#

and save server id and prefix in json

sick coyote
slate swan
#

@vale wing you looking for devops FIRE ?

sick coyote
#

you need a database

keen trail
#

for real waiting 2 months for disk fix

keen trail
vale wing
#

Well bobux for example logs random 12 numbers every 30 minutes and db size doesn't exceed 2 MB

sick coyote
#

wym

slate swan
vale wing
#

Aw man you didn't even see the beast in action

#

Lots of stuff is automated already

#

Even extensions setup function

slate swan
#

dam and is the method named _auto_setup

vale wing
#

I forgor

slate swan
#

how can you not know your bot code

#

dam nice manager

vale wing
#

Cause I wrote that half of year ago

vale wing
#
    def auto_setup(self, module_name: str) -> None: 
         module = importlib.import_module(module_name, None) 
         sys.modules[module_name] = module 
         members = inspect.getmembers( 
             module, 
             lambda x: inspect.isclass(x) and issubclass(x, commands.Cog) and x is not Cog, 
         ) 
         for member in members: 
             self.add_cog(member[1](self)) 
  
         self.log.ok("%s loaded", module_name)```
keen trail
unkempt canyonBOT
#

src/bot.py lines 35 to 40

def _auto_setup(self, path: str) -> None:
    module = importlib.import_module(path)
    for name, obj in inspect.getmembers(module):
        if inspect.isclass(obj) and issubclass(obj, commands.Cog) and name != "BaseCog":
            self.add_cog(obj(self))
            self.logger.info(f"Loaded {name} cog.")```
keen trail
#

guys u know whats the worst thing to do to slow down ur bot?

vale wing
#

Mine has more lines!

slate swan
#

i guess asher modified your code a bit and i stole it from him and modify it also

vale wing
#

Probably

slate swan
vale wing
#

You just have condition in separate if statement and I have that in lambda

slate swan
#

you are not unpacking the members

#

in for loop

vale wing
#

Yeah could do that as py for _, cog in members

#

What other kinds of automations were you thinking of

slate swan
#

i meant more like outside of python code scope

#

dockerize if not already, github actions to auto update code on remote server on new version

vale wing
#

Already done

#

And panda is currently working on dynamic update system

keen trail
#

hm i got ai but its useless in my bot what do i do with it?

vale wing
#

Analyze its usage

#

Maybe it's not that useless

keen trail
#

it is

#

no one uses it bc servers where its enabled died

slate swan
keen trail
#

and the ai is smarter than gpt 3 i think

vale wing
#

🥶

keen trail
#

bc isnt trained on examples

#

and got bigger brain

slate swan
#

what you use for it?

keen trail
slate swan
keen trail
#

it isnt using library

vale wing
#

LaMDA

keen trail
#

its coded in python

vale wing
#

Tensorflow

keen trail
#

nope

vale wing
#

Scikit

slate swan
#

you just coded an AI neural network from scratch?

vale wing
#

ChatterBot

umbral flame
#

how can i use the ephemal feature on embeded messages, i tried this but its still visable to everyone:

#code by telcaum
@bot.command()
async def vote(ctx):
  await ctx.send(embed=discord.Embed(
      title="vote register",
      description=f'''hello {ctx.author.name} 

(logged in as: user {((str(ctx.author.id)))})

now type &&f for the full list of canidates and other information'''),
  ephemeral=True)
slate swan
#

without tensorflow or pytorch

keen trail
#

only uses re to delete the no needed things from message

keen trail
vale wing
#

I remember how I once had "ai" bot

slate swan
#

!d discord.ext.commands.Context.send

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

Sends a message to the destination with the content given.

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

For interaction based contexts this does one of the following...
slate swan
#

ephemeral (bool) –

Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes. This is only applicable in contexts with an interaction.

New in version 2.0.

vale wing
# keen trail how it was?

So basically when you would make any statement like "sky is blue" bot would reply with "Um actually, sky isn't blue 🤓"

umbral flame
#

can i use dms?

keen trail
vale wing
#

No nlp ofc, pure regex

slate swan
#
if question.lower() == "is sky blue?":
keen trail
#

and have a very nice data collection system

slate swan
umbral flame
vale wing
#

I should probably make it public for educational purposes or whatever

keen trail
umbral flame
slate swan
#

!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**.
vale wing
#

How it works

keen trail
keen trail
vale wing
#

K sure

slate swan
#

bunch of if else blocks

keen trail
#

just by chatting with bot

#

alr i tell how time zone collection works

#

it analizes what time u use bot most time

#

and by weather option

#

which country weather is used the msot

#

most

vale wing
keen trail
#

it analizes timezone map

#

and gets timezone

vale wing
keen trail
#

and with that can get ur location

#

lemme see

keen trail
#

anser?

vale wing
vale wing
keen trail
#

hm ok

#

this one?

#

i saw train files

#

but no corpuses

vale wing
#

AIAS uses random forest classifier

slate swan
#

you know its serious when bot is inside utils

keen trail
#

mine works nearly like gpt

keen trail
#

hm am looking for a Collab with someone

#

am really bored

#

everyone stopped chatting 😓

slate swan
#

if i wanted to get the ID members robux clothign games and games visit how would i get all those values?

right now the embed is in a embed object

oblique laurel
slate swan
oblique laurel
#

Get the message id, then print out the contents to see what it looks like internally

#

From there you can see the pattern and try to parse the values out

oblique laurel
#

What does printing that give you?

silent ermine
#

Is there another alternative to getting the number of messages in a channel for 1 day other than using .history()?

slate swan
# oblique laurel What does printing that give you?

[EmbedProxy(value='``32374568``', name='**ID**', inline=True), EmbedProxy(value='``0``', name='**Members**', inline=True), EmbedProxy(value='``0``', name='**Robux**', inline=True), EmbedProxy(value='``0``', name='**Clothing**', inline=True), EmbedProxy(value='``0``', name='**Games**', inline=True), EmbedProxy(value='``0``', name='**Game Visits**', inline=True)]

this

oblique laurel
#

see if it's **ID**

slate swan
#

i doubt it do you think there's a easier way

oblique laurel
#

I'm making a guess, if it works like I think it won't be that bad

oblique laurel
slate swan
oblique laurel
#

So you can just use a dict comp here

oblique laurel
slate swan
oblique laurel
#

Might want field.name[2:-2] bc bold

slate swan
oblique laurel
#

Wdym? The dict comp?

slate swan
oblique laurel
#

From this discord, you can pick up lots of stuff around here

slate swan
oblique laurel
#

Yeah, I learned to do things the "long" way through tutorials but learned how to write it a different way from here

slate swan
#

can someone help me make a discord bot i am new to this bot making xd

unkempt canyonBOT
hasty pike
#

Discordpy

slate swan
#

oh anything else i need to learn to make a bot like a special program?

tame nymph
hasty pike
#

Python and OOP that's it

slate swan
#

well i assume youtube has tutorails for it right?

hasty pike
#

You know python?

slate swan
#

somewhat not too advanced

hasty pike
#

You need to be good at OOP for making bots

tame nymph
hasty pike
slate swan
#

can't i just host it on my pc

hasty pike
#

You can run bot in 4 lines

tame nymph
#

(context: I am C++ bot dev)

hasty pike
slate swan
tame nymph
#

alr I'm gonna go u can handle skids

hasty pike
#
import discord
from discord.ext import commands

bot = commands.Bot(intents=discord.Intents.default())

bot.run("TOKEN")
#

That's it

slate swan
#

no like is this where i run it

#

i always used online stuff so i am not sure on windows

hasty pike
#

Well seems like you need a good editor

tame nymph
hasty pike
tame nymph
#

ur talking to a person who has used nano to code

slate swan
#

damn

hasty pike
#

Ur talking to a person who never walked out of vs code

tame nymph
#

vs code is good

#

@slate swan u should use vscode

hasty pike
#

It's easiest tbh

slate swan
#

its to big and kinda to powerful

#

for an intel hd 3000

hasty pike
slate swan
#

and the idea i wanna make for it i might need help more than oop

#

like actual help cause it kinda weird

hasty pike
#

Are you making a nuclear activation bot?

slate swan
#

can i just say what it is

hasty pike
#

Sure why not

slate swan
#

i want it to be able to send me announces in a channel when i post something new on curseforge for my mod ya know

hasty pike
#

What is curseforge

slate swan
#

website for mods

hasty pike
#

Never heard

slate swan
#

can i do that though

hasty pike
#

You need API

slate swan
#

api for the website right?

hasty pike
#

Read, you'll understand your limits

#

What you can do and what not

#

Ig
Note: Any registered account which is not a game developer and did not request a key, will be deleted

slate swan
#

so its risky if i not game developer and did not request a key

#

damn

hasty pike
#

Figure it out "I have 0 knowledge of it"

slate swan
#

oh right sorry

hasty pike
#

Trynna not to give you false information

slate swan
#

is that possible to make alone?

hasty pike
#

jar file is made of java program

#

And txt files are just Normal text files

slate swan
#

so i made some code in idle shell can i run on it?

hasty pike
#

What exactly you want

slate swan
#

to run the code so the bot works?

hasty pike
#

Isn't it better to run file instead pithink

slate swan
#

so like save it and run it?

hasty pike
#

Yes

slate swan
#

so i ran it

#

like as a normal python file but i can't see it so i assume it worked right

hasty pike
#

You made code yourself?

slate swan
#

just tiny but to see if it'll respond or not

#

i still learning

hasty pike
#

Which code did you run

slate swan
#

python?

hasty pike
#

Show?

slate swan
#

and i did get help from yt

#

do i just send copy and paste

#

@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
# Start the update announcement task when the bot is ready
check_for_updates.start()

@tasks.loop(minutes=15) # Run the task every 15 minutes
async def check_for_updates():
page = requests.get(CURSEFORGE_URL)
if page.status_code == 200:
soup = BeautifulSoup(page.content, 'html.parser')
update_element = soup.find('div', {'class': 'b-post__date'})
if update_element:
latest_update = update_element.text.strip()
await announce_update(latest_update)
else:
print(f"Failed to fetch page. Status code: {page.status_code}")

hasty pike
#

This isn't full

slate swan
#

i am still working this is what i did so far

hasty pike
#

It's incomplete

slate swan
#

oh then time to work more to finish

hasty pike
#

You Didn't define bot and didn't logged in

#

I wonder why it didn't throw any error

slate swan
hasty pike
#

No idea

#

I've installed on my terminal or pc whatever you want to call it

slate swan
#

linux or windows?

hasty pike
#

Windows

slate swan
#

can you tell me how then i use windows too

hasty pike
#

Ig you need someone much more experienced than me to guide you here

#

Or maybe just 'YouTube'

somber sky
#

how would i make a command that creates emojis

sick birch
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.
somber sky
# sick birch !d discord.Guild.create_custom_emoji
 in_file = open("emojitest.png", "rb")
 data = in_file.read()
 in_file.close()
 await interaction.guild.create_custom_emoji(name="test", image=data)```


how would i make it where it looks for the file inside a folder
glad cradle
#

not related to your question but reading and opening a file is a blocking operation

#

!pypi aiofiles

unkempt canyonBOT
glad cradle
#

you should use this

merry cliff
#

damnnn never knew that

lucid kite
#

for an image it's fine imo

honest laurel
glad cradle
#

while opening a file isn't that blocking, reading one definitely is

shrewd apex
#

^^

#

opening a file just internally places a pointer/cursor to file content in 0th index

tepid dagger
#

whats the command for dming a user

#

i want to take text from one user and dm it to a separate user

naive briar
tepid dagger
#

ig

#

yea

naive briar
#

!d discord.User.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**.
tepid dagger
#

how do you find the user you want to dm

dawn stratus
#

I am running into a problem here, let me give you a code example:

@bot.event
async def on_message(message):
  x = await getX()
  print(x)
  await message.channel.send(x)

async def getX():
  return 10

Log:

None

For some reason it always outputs None

naive briar
unkempt canyonBOT
#

get_user(id, /)```
Returns a user with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
naive briar
unkempt canyonBOT
#

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

001 | 10
002 | 10
003 | 10
naive briar
#

Doubt it

tepid dagger
naive briar
#

What's confusing about it

tepid dagger
#

wait discord.Client.get_user gets the id of the user who ran the command right

#

its worded as "Returns a user with the given ID" which sorta sounds like you need to already know the id

naive briar
#

No, read the docs

tepid dagger
#

wait so you already need to have the id

naive briar
#

Yes?

tepid dagger
#

is there a discord.Client.get_id or smth

naive briar
#

No

tepid dagger
#

than how do u get the id in the first place

naive briar
unkempt canyonBOT
tepid dagger
#

ok ty

dawn stratus
#

!e

import asyncio


async def main():
    x = await getX()
    print(x)
    x = await getX()
    print(x)
    x = await getX()
    print(x)

async def getX():
    return 10

asyncio.run(main())
unkempt canyonBOT
#

@dawn stratus :white_check_mark: Your 3.11 eval job has completed with return code 0.

001 | 10
002 | 10
003 | 10
dawn stratus
#

huh

#

dosent work for discord for sum reason

naive briar
#

What do you mean dosent work for discord for sum reason?

keen trail
#

?

#

hm am bored

harsh orbit
#

How I can get author avatar url
ctx.author.avatar_url not working

slate swan
#

!d discord.Member.avatar

unkempt canyonBOT
#

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

Author*

slate swan
#

Author is of type Member

harsh orbit
#

ctx.author.avatar?

slate swan
#

anyone here use pyhcarm?

#

for python ofcourse

buoyant quail
#

Yes pithink

formal basin
#

what is the error for a user with dms off?

slate swan
#

!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**.
slate swan
#

Raises
HTTPException – Sending the message failed.

formal basin
#

could I do that?

slate swan
#

yes but you need to import it from discord module

formal basin
#

from discord import HTTPException

#

like that

#

or discord.ext?

slate swan
#

!d discord.HTTPException

unkempt canyonBOT
#

exception discord.HTTPException(response, message)```
Exception that’s raised when an HTTP request operation fails.
slate swan
#

under discord

formal basin
#

ok

formal basin
slate swan
#

you wanna have same case for two errors or two different cases for two exceptions

formal basin
#

different

slate swan
#
try:
    ...
except Exception:
    ...
except OtherException:
    ...
formal basin
#

I never new

#

thanks

naive briar
#

!e

try:
    0 / 0
except ZeroDivisionError:
    print("No")
except ValueError:
    print("Also no")
unkempt canyonBOT
#

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

No
slate swan
#

if you wanted the same case for many errors you can do ```py
try:
...
except (Exception, OtherException):
...

slate swan
#

!E py try: raise Exception except* Exception as e: print(e.exceptions)

unkempt canyonBOT
#

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

(Exception(),)
formal basin
#

wait you know if the bot tries to kick its self will it raise the HTTPException error?

slate swan
#

!d discord.Guild.kick

unkempt canyonBOT
#

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

Kicks a user from the guild.

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

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

Why would someone make their bot try to kick itself

slate swan
#

yes it will be HTTPException

formal basin
slate swan
#

Raises
Forbidden – You do not have the proper permissions to kick.

HTTPException – Kicking failed.

#

Forbidden is subclass of HTTPException

formal basin
#

wait if I check if the member is itself how can I make it go the on_app_command_error

buoyant crescent
#

hi i'm trying to use the clash royal api, but when i imports the requests. I have an error "requests" is not accessedPylance Import "requests" could not be resolved from sourcePylancereportMissingModuleSource (module) requests
This is my code ```python
import discord
from discord.ext import commands
import os
from discord import app_commands
from apikeys import *
import requests

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

api_key = ''

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

@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Pokemon Unite", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")

bot.run((BOTTOKEN))```

slate swan
#

you can create own exception and handle it in error handler

formal basin
slate swan
#

cause pylance isnt actual interpreter

#

also tip
for discord bot i wouldnt recommend using requests since its blocking (slowing your discord bot) use aiohttp instead

#

if you wanna find out more check out !blocking command

buoyant crescent
buoyant crescent
naive briar
#

aiohttp is installed when you install discord.py or its forks

slate swan
#

Traceback

buoyant crescent
#

!blocking

unkempt canyonBOT
#
Asynchronous programming

Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

slate swan
#

!rule 4

unkempt canyonBOT
#

4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.

weak ingot
#

is it possible to make a discord slash bot and run it as a bot not a client

slate swan
#

yes it is

weak ingot
#

i cant do it

slate swan
#

what did you try?

naive briar
#

What's the problem then

weak ingot
#

tried this

#

import discord
from discord.ext import commands
from discord_slash import SlashCommand

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True

MY_GUILD = discord.Object(id=1133019868292186133)  # replace with your guild id

bot = commands.Bot(command_prefix="/", intents=intents)
slash = SlashCommand(bot, sync_commands=True)  # Create a SlashCommand instance

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')

@slash.slash(name="hello", description="Greets the user.")
async def hello(ctx):
    await ctx.send(f'Hi, {ctx.author.mention}!')

@slash.slash(name="add", description="Adds two numbers together.")
async def add(ctx, first_value: int, second_value: int):
    result = first_value + second_value
    await ctx.send(f'{first_value} + {second_value} = {result}')

@slash.slash(name="send", description="Sends the provided text.")
async def send(ctx, text_to_send: str):
    await ctx.send(text_to_send)

@slash.slash(name="joined", description="Shows when a member joined the server.")
async def joined(ctx, member: discord.Member = None):
    member = member or ctx.author
    join_date = member.joined_at.strftime('%Y-%m-%d %H:%M:%S')
    await ctx.send(f'{member.display_name} joined at {join_date}')

@slash.slash(name="test", description="A test command.")
async def test(ctx):
    await ctx.send("This is a test command!")

def main():
    bot.run('MTE----UgY')

if __name__ == "__main__":
    main()
slate swan
#

discord_slash is outdated discord.py already has slash commands built in

weak ingot
#

fady@debian-et8re0j:~/Documents/Code/public/FlareMod$ python3 main.py
Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/main.py", line 3, in <module>
from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'
fady@debian-et8re0j:~/Documents/Code/public/FlareMod$

slate swan
#

remove discord_slash? yes

weak ingot
#

okie

weak ingot
# slate swan remove `discord_slash`? yes
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.message_content = True

MY_GUILD = discord.Object(id=1133019868292186133)  # replace with your guild id

bot = commands.Bot(command_prefix="/", intents=intents)
slash = SlashCommand(bot, sync_commands=True)  # Create a SlashCommand instance

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')

@slash.slash(name="hello", description="Greets the user.")
async def hello(ctx):
    await ctx.send(f'Hi, {ctx.author.mention}!')

@slash.slash(name="add", description="Adds two numbers together.")
async def add(ctx, first_value: int, second_value: int):
    result = first_value + second_value
    await ctx.send(f'{first_value} + {second_value} = {result}')

@slash.slash(name="send", description="Sends the provided text.")
async def send(ctx, text_to_send: str):
    await ctx.send(text_to_send)

@slash.slash(name="joined", description="Shows when a member joined the server.")
async def joined(ctx, member: discord.Member = None):
    member = member or ctx.author
    join_date = member.joined_at.strftime('%Y-%m-%d %H:%M:%S')
    await ctx.send(f'{member.display_name} joined at {join_date}')

@slash.slash(name="test", description="A test command.")
async def test(ctx):
    await ctx.send("This is a test command!")

def main():
    bot.run('MTE---UgY')

if __name__ == "__main__":
    main()
#

fady@debian-et8re0j:~/Documents/Code/public/FlareMod$ python3 main.py
Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/main.py", line 12, in <module>
slash = SlashCommand(bot, sync_commands=True) # Create a SlashCommand instance
NameError: name 'SlashCommand' is not defined
fady@debian-et8re0j:~/Documents/Code/public/FlareMod$

slate swan
#

if you dont have discord_slash you cant create SlashCommand

weak ingot
slate swan
#

look at the example'

weak ingot
#

okie

weak ingot
#

how to chage it to a bot

slate swan
#

subclass a Bot and not Client

weak ingot
#

okie

slate swan
#

but then you dont have to create tree instance

weak ingot
#

okie

past dome
#

oh yeahhhhhhh

#

im new here

#

but ihave a bot

weak ingot
#

@past dome HI

past dome
#

hello hehe

weak ingot
slate swan
#

cause you are using .command() decorator

#

its for prefixed commands

naive briar
#

Also, you don't have the message_content enabled, so your bot cannot read messages

unkempt canyonBOT
#

examples/app_commands/basic.py line 41

@client.tree.command()```
slate swan
#

this tree in between matters

naive briar
#

And app_commands.describe is for app commands

weak ingot
#

but you said i donnt nnneed a tree

naive briar
#

You don't need to define a tree

slate swan
#

yes you dont need to create one cause Bot already creates one for you

weak ingot
#

okie

tepid dagger
#

its like await User.send(“stuff”) would you have to do like User = “id” or smth

#

or am i being dumb

cloud dawn
#

Client over Bot any day with slash commands.

tepid dagger
#

true

still phoenix
#

Hey there. Im very new to discord bots and im trying to fix an old python script.
Im using asyncio.get_event_loop().create_task(run_bot()) To start my "main" function loop.
When trying to run it, i get the following message RuntimeWarning: coroutine 'run_bot' was never awaited self._ready.clear()

How do I have to change this?

slate swan
#

show code

young dagger
#

Why is it not showing emojis?

slate swan
young dagger
# slate swan how does it look like in code?
    primary_path = random.choice(list(RUNES.keys()))
    secondary_paths = [path for path in RUNES.keys() if path != primary_path]

    primary_keystone = random.choice(RUNES[primary_path]["Keystone"])
    primary_keystone_emoji = f':{primary_keystone.replace(" ", "_")}:'

    secondary_path = random.choice(secondary_paths)
    secondary_lesser = random.choice(RUNES[secondary_path]["Lesser"])
    secondary_lesser_emoji = f':{secondary_lesser.replace(" ", "_")}:'

embed.add_field(name='Runes', value=f"{primary_keystone_emoji} - {primary_keystone}\n{secondary_lesser_emoji} - {secondary_lesser}",
                    inline=False)```
still phoenix
# slate swan show code

Its not the full code but it is about this

async def run_bot():
    location = "Duisburg"
    today = get_date_now()
    daily_prayer_times = get_daily_prayer_times(location, today)

    while True:
        if not run_bot_channels:
            # print('NO CHANNELS')
            await asyncio.sleep(10.0)
            continue
        
        time_now = get_time_now()
        await bot.get_channel('960804554910339085').send("Time: " + time_now)
        print("testttt")
        # await client.get_channel('800046347016863757').send(run_bot_channels)

        if is_next_day():
            today = get_date_now()
            daily_prayer_times = get_daily_prayer_times(location, today)

        # For testing purposes only:
        # daily_prayer_times = ['07:55', '07:56', '07:57', '07:58', '07:52']

        for i in range(len(daily_prayer_times)):
            if time_now == daily_prayer_times[i]:
                print("Sending prayer notification to channels!")
                if i == 0:
                    for channel in run_bot_channels:
                        bot_channel = bot.get_channel(channel)
                        await bot_channel.send('Wake Up - It\'s Fajr Time!')
                elif i == 1:
                    for channel in run_bot_channels:
                        bot_channel = bot.get_channel(channel)
                        await bot_channel.send('Take a Break - It\'s Dhuhr Time!')
                elif i == 2:
                    for channel in run_bot_channels:
                        bot_channel = bot.get_channel(channel)
                        await bot_channel.send('Make Wudhu - It\'s Asr Time!')
                elif i == 3:
                    for channel in run_bot_channels:
                        bot_channel = bot.get_channel(channel)
                        await bot_channel.send('Gather For Prayer - It\'s Maghrib Time!')
                else:
                    for channel in run_bot_channels:
                        bot_channel = bot.get_channel(channel)
                        await bot_channel.send('Don\'t Sleep Yet - It\'s Isha Time!')

        await asyncio.sleep(60.0)```
young dagger
#

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

slate swan
still phoenix
slate swan
#

use tasks and not a while True loop

#

!d discord.ext.tasks.loop

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 "discord.ext.tasks.Loop").
still phoenix
#

oh sick I will look into it. thanks alot ❤️

young dagger
still phoenix
young dagger
#

Is there any simplier way to do this?

guild = discord.utils.get(client.guilds, id=1135157269328302110)

# First emoji
primary_keystone_emoji = discord.utils.get(guild.emojis, name=primary_keystone.replace(' ', '_'))

# Second emoji
secondary_lesser_emoji = discord.utils.get(guild.emojis, name=secondary_lesser.replace(' ', '_'))```
slate swan
#

By putting \ before the Emoji itself on discord

young dagger
slate swan
slate swan
hasty coral
#

Other than on_invite_create and on_invite_delete are there any other invite based events?

slate swan
hasty coral
young dagger
#

So if we add the bot to another server, it should still use emojis from our server

slate swan
#

yeah thats how it works too

hasty coral
harsh orbit
#

Can I set too many values in one field in embed and if its yes so how?

slate swan
#

what does set too many values mean

harsh orbit
#

Wait

#

Look there is only one value can I add more?

  embed.add_field(name="Server1", value="not ok", inline=False)
slate swan
#

no you can only add one value to one field

#

but you can insert any text to it

#

with new lines too

harsh orbit
#

How they make this

#

That's titles?

slate swan
#

no that looks like description

harsh orbit
#

Description
Like this
Not this

slate swan
#

you can use markup in description

harsh orbit
#

Oh

#

Ok

#

Thx for help

slate swan
#

👍

keen trail
#

hm am bored

keen trail
slate swan
#

currently got this Rapptz/discord.py#9519

lament depotBOT
vale wing
#

We are just at stage of planning content for future version

keen trail
#

i can give u idea

slate swan
vale wing
#

K

vale wing
slate swan
#

someone wanna explain to me how python -m discord -v command works

unkempt canyonBOT
#

discord/__main__.py line 336

parser.add_argument('-v', '--version', action='store_true', help='shows the library version')```
vale wing
#

Just shows the version?

slate swan
#

surprising

keen trail
vale wing
#

Yes

keen trail
#

oh cool am owner of doggeł inc

slate swan
#

im owner of Google INC

vale wing
#

Oh mo

keen trail
slate swan
keen trail
#

uh ok

#

doggeł inc is something different than doge inc

vale wing
keen trail
vale wing
#

We need a way for spending bobux

slate swan
harsh orbit
#
@bot.event
async def on_ready():
  print("the bot is online")
  await bot.change_presence(status=discord.Status.dnd, activity=discord.Activity(type = discord.ActivityType.listening, name="Hustel Members"))
  channel = bot.get_channel(1136780399096385627)
  await channel.send("Online")

Why the bot status is online?

keen trail
#

had that too change in while

#

if not means there is bug

slate swan
#

when the new task list arrives? i need to know a deadline for current tasks @vale wing

vale wing
#

Currently no tasks

#

We are on stage of planning

#

They will be tomorrow I think

slate swan
#

ah so i got time to finish what im still doing

#

wait tomorow aniblobsweat

keen trail
buoyant crescent
#

hi i need help when i type a command i tell me that it is not found ```python
import discord
from discord.ext import commands
import os
from discord import app_commands
from apikeys import *
import aiohttp

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

cr_api_key = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6IjYzNDdlY2I3LTc0YTctNDQ0ZS04YzFiLTEwMTAzYTE2MTk2ZSIsImlhdCI6MTY5MTE0MjkxNCwic3ViIjoiZGV2ZWxvcGVyL2FkMzI0NWIxLTc2OTAtMWRlZi03MjVlLThkM2RlZTY5NTk0ZCIsInNjb3BlcyI6WyJyb3lhbGUiXSwibGltaXRzIjpbeyJ0aWVyIjoiZGV2ZWxvcGVyL3NpbHZlciIsInR5cGUiOiJ0aHJvdHRsaW5nIn0seyJjaWRycyI6WyIxOTcuMy4xMzUuMTAzIl0sInR5cGUiOiJjbGllbnQifV19.O7H1f9JjUb5Pr2RpCcaNmCG7lwhel07ySQE5nqkYOaDmDJyW_2bHYCSgQUssq5jg6sqrw0Vs5VJHyO-qVHCEXA'

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

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

@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.do_not_disturb, activity=discord.Streaming(name="Clash Royale", url="https://www.twitch.tv/mysterymom__"))
print("The bot is now ready")
print("--------------------")

bot.run((BOTTOKEN))```

naive briar
#

Put parentheses behind the @bot.command

naive briar
#

-> @bot.command()

#

Also you probably shouldn't share your api key of something

young dagger
buoyant crescent
#

ty

harsh orbit
#

How i can get meaaage tezt from message id

naive briar
#

!d discord.TextChannel.fetch_message

unkempt canyonBOT
#

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

Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
naive briar
#

!d discord.Message.content

unkempt canyonBOT
slate swan
buoyant crescent
#

I don't know if i can ask the question here but i want my bot to communicate with the clash royale api but they ask me a ip adress, do i need to enter a special one because it's a discord bot or i just need to enter my public ip ?

naive briar
buoyant crescent
#

the allowed ip adress

#

that can communicate with the api

#

( i host my bot in vs code)

buoyant crescent
#

i ask this question because i have created a key using my public ip adress and when i test a code it return me API Error - Status Code: 404

thin raft
#

that changed since the last time I visited it

#

try using ip 0.0.0.0

buoyant crescent
#

ok ty

thin raft
#

if not search for your public ip address and add it there

buoyant crescent
#

so it was not the ip ... API Error - Status Code: 403 {"reason":"accessDenied.invalidIp","message":"Invalid authorization: API key does not allow access from IP

thin raft
#

yeah it's the ip

#

why don't you remove the ip?

#

there¡s a cross to the right

buoyant crescent
buoyant crescent
maiden fable
cloud dawn
hasty pike
slate swan
cold sonnet
#

now everybody's gonna ignore me

maiden fable
cold sonnet
#

hi

#

I understand that nobody said meh

#

but I still spawned

maiden fable
#

Meh

cold sonnet
#

hi

maiden fable
#

I'm not in denial

cold sonnet
#

I am

#

I have a reputation as denial already

#

he was in denial for losing a game probably

#

so y'all just

#

occasionally still come back to this channel and help people

#

nah this channel is long dead

cloud dawn
hasty pike
somber sky
#

how would i make a command where you insert a server id into a list? I have a list with server id's so if the server id isnt there then the bot will just leave the server, im trying to make a command where i can insert a server id into that list with a command

unkempt canyonBOT
#

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

Leaves the guild.

Note

You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
upbeat ice
#

Choose your poision for how you wish to store/validate server ids

slate swan
#

Discord api will validate it for you

hasty pike
#

For guild in bot.guilds:

#

Leave all 🤡

tall temple
#

hey can someone help me with that case pls ?

slate swan
#

!e x = "something" + x

unkempt canyonBOT
#

@slate swan :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "/home/main.py", line 1, in <module>
003 |     x = "something" + x
004 |                       ^
005 | NameError: name 'x' is not defined
tall temple
slate swan
#

show full code

tall temple
#

category : discord.Option....

slate swan
#

you gave me two screenshots that dont even show code lines how am i supposed to know where its placed

tall temple
#

@slate swan

#

sorry

slate swan
#

.. whats so hard about sharing the function code?

tall temple
# slate swan .. whats so hard about sharing the function code?
@default_permissions(administrator = True)
@bot.slash_command(title = "ticketpanel", description = "Send the ticket panel")
async def ticketpanel(ctx, category : discord.Option(str, "Write here the category id where the tickets will be created")) :

    pb = Button(label = "🛒 PURSHASE", style = discord.ButtonStyle.grey)
    eb = Button(label = "💱 EXCHANGE", style = discord.ButtonStyle.grey)
    hb = Button(label = "📌 HELP", style = discord.ButtonStyle.grey)
    mv = View()
    mv.add_item(pb)
    mv.add_item(eb)
    mv.add_item(hb)


    async def pb_callback(interaction) :
        category = discord.utils.get(interaction.guild.categories, id = category)
        channel = await ctx.guild.create_text_channel(name=f'🛒・{interaction.user.name}', category = int(category))
slate swan
#

you use category inside pb_callback function

glacial idol
#

Do you know if your bot has a feature where you can go into any server and set its prefix individually? When someone wants to change its prefix on its server, it doesn't respond guys i need your help?

tall temple
glacial idol
#

@commands.hybrid_command( name="prefix", aliases=["setprefix", "prefixset"], help="Allows you to change prefix of the bot for this server") @blacklist_check() @ignore_check() @commands.has_permissions(administrator=True) @commands.cooldown(1, 10, commands.BucketType.user) @commands.max_concurrency(1, per=commands.BucketType.default, wait=False) @commands.guild_only() async def _prefix(self, ctx: commands.Context, prefix): data = getConfig(ctx.guild.id) mod = data["mod"] if ctx.author.id in mod: data["prefix"] = str(prefix) updateConfig(ctx.guild.id, data) await ctx.reply(embed=discord.Embed( description= f":tick: | Successfully Changed Prefix For **{ctx.guild.name}**\nNew Prefix for **{ctx.guild.name}** is : `{prefix}`\nUse `{prefix}help` For More info .", color=0x50101)) else: await ctx.send(" le le

slate swan
glacial idol
#

i know but my bot not responding me watch do anyone know how i can fix it?

tall temple
slate swan
#

you cant use varriable as typehint

tall temple
#

or i have to write = category ?

slate swan
#

i doubt it will work

slate swan
glacial idol
tall temple
slate swan
tall temple
slate swan
#

debug it and see

glacial idol
#

@slate swan are you understand?

#

I'm really didn't know much know python

slate swan
#

can you put print("something") on top of your command to see if it runs?

cloud dawn
#

He meant inside it.

#

So above the data variable.

glacial idol
slate swan
#

man you really dont get python

#

i would learn it before starting a discord bot project

glacial idol
#

🤣 🥹 😳

#

yes you are right i really didn't know

#

muxh

glacial idol
glacial idol
#

heheheh

tall temple
round knoll
slate swan
#

@hushed galleon that was quick fix by Rapptz

round knoll
# slate swan What do you mean by "doesn't work"

it used to print that it was checking for roles etc, it was working exactly as intented. but now nothing works like it should. i do get my print that says the bot connected to the discord API

round knoll
somber sky
round knoll
#

looks like my loop isnt starting, not sure of the syntax for that, do i just call my function in my if main statement at the end of my file?

#
if __name__ == "__main__":
    bot.run(disc_token)
    check_twitch_online_streamers()
slate swan
#

Everything after bot.run wont run

heavy comet
#

someone knows how to detect when member is changing of voice channel ?

round knoll
#

ok ive changed the code, i do get more print statements now

slate swan
unkempt canyonBOT
#

discord.on_voice_state_update(member, before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") changes their [`VoiceState`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceState "discord.VoiceState").

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

so, if i give myself the role, the bot will remove it, and give me proper print statements.. so i know its got proper rights

also, after.activities does have stuff in it

2023-08-04 19:47:44----------ZeddyBot is checking for roles----------
2023-08-04 19:47:44----------ZeddyBot is Removing LIVE role from renegadezed----------
(<Spotify title='The Startup' artist='Harris Heller' track_id='00WrXhzCC2DO68p5YFKH1A'>,)
2023-08-04 19:47:44----------ZeddyBot is checking for roles----------
#

ok with the API update, i think the on_member_update event does not hold the activity event anymore, i need to switch to on_presence_update

can anyone confirm my findings?

#

this is my code now.. the problem now, is that the after object wont have the roles attribute..

@bot.event
async def on_presence_update(before, after):
    print(
        f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------ZeddyBot is checking for roles----------"
    )
    if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
        if LIVE_ROLE_ID in after._roles:
            return
        else:
            print(
                f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------ZeddyBot is Giving LIVE role to {after.name}----------"
            )
            await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))

    else:
        if LIVE_ROLE_ID in after._roles:
            print(
                f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------ZeddyBot is Removing LIVE role from {after.name}----------"
            )
            await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
hushed galleon
# round knoll ok with the API update, i think the on_member_update event does not hold the act...

https://discordpy.readthedocs.io/en/stable/migrating.html#presence-updates-now-have-a-separate-event

Presence updates (changes in member’s status and activity) now have a separate on_presence_update() event. on_member_update() event is now only called on member updates (changes in nickname, role, pending status, etc.).

From API perspective, these are separate events and as such, this change improves library’s consistency with the API. Presence updates usually are 90% of all handled events so splitting these should benefit listeners that were only interested in member updates.

round knoll
#

ive switched to on_presence_update to get access to activity

hushed galleon
#

can you show the error traceback you got? im not sure what you mean by after not having the roles attribute

round knoll
#

oh, ive got no error

#

wait so its working now? simple as that?

hushed galleon
#

uhh i guess so

round knoll
#

cause it's not removing the role if i manually give it to myself, which it should, since im not "streaming"

hushed galleon
#

right, cause changing your roles only triggers on_member_update

#

i guess the cleanest solution would be registering the same function as a listener for both events

#

e.g. py @bot.listen("on_member_update") @bot.listen("on_presence_update") async def update_live_role(before, after): ...

round knoll
#

oh wow, i didnt know you could stack those decorators

round knoll
#

huge thanks! ❤️

heavy comet
compact cairn
#

is there any other way to define member: discord.member in arg after prefix

somber sky
#

how do i make a command where you insert an id, and that id goes into a list

frozen pivot
#

shawneey can you give me some more context

tepid dagger
# naive briar !d discord.User.send

can i use this to dm the same user each time, even if the user isn’t running the command if i have the user id, i couldn’t find info about that lol

slate swan
#

!d discord.ext.commands.Bot.get_user

unkempt canyonBOT
slate swan
#

!d discord.ext.commands.Bot.fetch_user

unkempt canyonBOT
#

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

Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.

Note

This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_user "discord.ext.commands.Bot.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
slate swan
#

@tepid dagger

tepid dagger
#

no but how do i write a dm to the user once i have the id

#

ik how to get the id

#

thats my question bc i am bad at coding

slate swan
#

?? Literally shown you

#

How to get user from id

tepid dagger
#

how do i dm the user once i have the id

slate swan
#

did you even take that 5 seconds to open the docs i linked?

somber sky
slate swan
#

this returns User

tepid dagger
#

yea

slate swan
#

and when you have User you can send him message

#

!d discord.User.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**.
tepid dagger
#

is User the actual user

slate swan
#

yeah what else

tepid dagger
#

idk

#

wait do you write it as await User.send(“stuff”)

#

or do you have to define “User”

slate swan
#

User is just a class

#

you need to get User class instance

#

and if you wanna get it from id

tepid dagger
#

how

slate swan
#

use the methods i linked

tepid dagger
#

wait so get_user(id,)

#

will give “User”?

slate swan
#

Return type
Optional[User]

is that unclear or what

tepid dagger
#

and than u can use User.send(“stuf”) or am i being dumb

slate swan
#

why dont you try?

tepid dagger
#

ok

#

good idea

#

wait what

somber sky
tepid dagger
#

im tryna get a user to send in text

#

and it’ll dm it to one person

slate swan
tepid dagger
#

is get_user(id) the entire line

slate swan
#

its a method of Bot instance

#

or Client

tepid dagger
#

so client.get_user(id)?

slate swan
#

if you named your instance client, yes

tepid dagger
#

ok

#

than how do u dm it to the user

#

await User.send(“stuff”)

slate swan
somber sky
#

lol

tepid dagger
#

ok

#

lol sry im new to using apis

somber sky
#

your fine lol

tepid dagger
#

it says “User” not defined

naive briar
#

That's just Python in general, not discord.py

slate swan
#

and use tihs method on it

tepid dagger
#

so User = client.get_user(id)?

slate swan
#

yes in overall but dont name it as class name

#

user will be better name

tepid dagger
#

user = client.get_user(id)

#

await user.send(“stuff”)

#

wait what

#

it says “User” not defined

#

do i have to make user = User(client.get_user(id)) or smth

slate swan
#

no, why

#

it already returns user so why cast it to User

tepid dagger
#

so the code should be

#
  await user.send(“stuff”)
slate swan
#

dont ask me just try

tepid dagger
#

i did

#

it says “User” not defined

slate swan
#

show code and traceback then

tepid dagger
#

NameError: name ‘User’ is not defined

#

ln 31 await user.send(“stuff”)

naive briar
#

!traceback

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.

slate swan
#

full traceback

tepid dagger
#

ok

#

bruh its not copying

slate swan
#

i belive its so small you can screen shot it

tepid dagger
#

ok

slate swan
#

now go to line 31

#

and resolve why you still have User here

tepid dagger
#

i don’t

naive briar
#

The error said otherwise

slate swan
#

error says otherwise

#

lol

tepid dagger
#

bruh i don’t

#

witw

#

i think i screen shotted the wrong error msg 💀

slate swan
#

then show line 31

tepid dagger
#

nvm

#

it works now

slate swan
#

👍

tepid dagger
#

i forgot to remove parentheses that i forgot i added lol

somber sky
somber sky
#

oh, thanks sorry didnt know there was a channel for it

slate swan
#

no worries

somber sky
#

i put the server id in the list but for some reason the bot still left the server?

granite agate
#

Does anyone here know how to use the riot api?

somber sky
slate swan
granite agate
slate swan
#

Like you said again the error itself is with riot api and not discord bot

#

what can i do ?

maiden fable
#

.avatar.url

#

Not _

slate swan
#

ty

#

but it’s didn’t work

maiden fable
slate swan
#

yes

maiden fable
slate swan
#

okay

#

In my code it's about in a channel with "! Feedback (message)" what to write and when you send it, the message is automatically deleted and replaced in an embed. above should be the author name and image of the sender of the message.

maiden fable
#

Error not the objective

slate swan
#

okay

maiden fable
#

Where's the code for checking balance?

slate swan
maiden fable
#

Are you using a database or what?

maiden fable
slate swan
#

wait

maiden fable
#

You ain't committing the changes, thus the balance isn't being updated on the db, it's only being changed locally

slate swan
maiden fable
#

Instead of client

slate swan
#

omgg

#

@maiden fable thank you very much

maiden fable
#

What module r u using to access the database?

#

motor?

winter token
#

except commands.CommandOnCooldown as error:
            embed = discord.Embed(title="Cooldown", description=f"Try again <t:{int(time.time()+error.retry_after)}:R>", colour=discord.Colour.red())
            await ctx.reply(embed = embed)```
#

raise CommandOnCooldown(bucket, retry_after, self._buckets.type) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 86395.70s

slate swan
#

ok

winter token
#

how do i handle error for cooldown inside except

naive briar
#

You don't

#

The error will be sent to the command's error handler, not inside the command

dense mesa
#

Anyone with some Bot coding experience i could really use your help right now.

Im trying to develop my code and instead of having all the command and jargon in one .py file. I wanted to have say a base file for the bot '''edox.py''' , a api/key storage file '''.env''' and then another file that would store the commands '''cogs/moderation.py''' but when i use this method the bot stops responding. But does initially log in.

dense mesa
#

🤣 haha... Nvm i figured it out

formal basin
#

i have a anti bad word system. lets say this is my list = ["test1", "test2"] people can bypass it by doing "test1test2"

#

how can I fix that?

naive briar
#

No one can tell if they don't know how you implemented it

upbeat gust
upbeat gust
formal basin
#

oh ok let me show you

upbeat gust
formal basin
#

and it lets admins say bad words

formal basin
# upbeat gust We dont know how to fix your system if we dont know how your system works
@client.listen()
async def on_message(message):
    if message.author.id == client.user.id:
        return
    
    key = f'antibadwords:{message.guild.id}'
    if r.exists(key):
      if profanity.contains_profanity(message.content) or profanity.contains_profanity(replaceDoubleCharacters(message.content)):
        await message.delete()
        embed = discord.Embed(title="No bad words please", description=None)
        embed.set_footer(text="Censored by better_profanity")
        log = r.get(f"logs:{str(message.guild.id)}")
        await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
        embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
        embed.add_field(name="Reason", value="contained bad words")
        embed.set_footer(text="Censored by better_profanity")
        log2 = int(log.decode("utf-8"))
        logging = client.get_channel(log2) or await client.fetch_channel(log2)
        await logging.send(embed=embed)
        print(f"1bad word detected logs: {message.guild.id}")```

this is my system
#

I use the better_profanity package

upbeat gust
upbeat gust
formal basin
upbeat gust
#

why are they admins if they dont even follow your rules

formal basin
#

idk

upbeat gust
upbeat gust
#

there's no way to 100% block all profanity, people will always find new ways to say the words

upbeat gust
formal basin
#

let me show you

#

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

formal basin
#

this is to check if people swear using emojis

upbeat gust
formal basin
#
@client.listen()
async def on_message(message):
    if message.author.id == client.user.id:
        return
    
    message_content = message.content.lower()
    special_characters = r"[.\/,'|*=\-_`!<>+$%^?!1234567890@]"
    string_without_special_characters = re.sub(special_characters, "", message_content)
    key = f'antibadwords:{message.guild.id}'
    if r.exists(key):
     if profanity.contains_profanity(string_without_special_characters) or profanity.contains_profanity(replaceDoubleCharacters(string_without_special_characters)):
          print("test2")
          await message.delete()
          embed = discord.Embed(title="No bad words please", description=None)
          embed.set_footer(text="Censored by better_profanity")
          log = r.get(f"logs:{str(message.guild.id)}")
          await message.channel.send(f"{message.author.mention}", embed=embed, delete_after=20)
          embed = discord.Embed(title="Message Deleted", description=f"{message.author}'s message was deleted")
          embed.add_field(name="Reason", value="contained bad words")
          embed.set_footer(text="Censored by better_profanity")
          log2 = int(log.decode("utf-8"))
          logging = client.get_channel(log2) or await client.fetch_channel(log2)
          await logging.send(embed=embed)
          print(f"2bad word detected logs: {message.guild.id}")``` this one is for people who put special characters between the letters
#

!pate

unkempt canyonBOT
#
Did you mean ...

» windows-path
» pathlib
» relative-path

formal basin
#

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

upbeat gust
#

Still doesnt account for character variations

#

check out this for some regex

upbeat gust
#

Okay? and?

formal basin
upbeat gust
#

cool

upbeat gust
upbeat gust
vocal laurel
formal basin
#

how can I check if a user is not in the guild?

#

if user not in guild?

#

well interaction.guild for slash command

slate swan
#

!d discord.Guild.members

unkempt canyonBOT
shrewd apex
#

!traceback

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.

slate swan
#

We don't know, you tell us what's not working

shrewd apex
#

also is button.callback even allowed to be used like that

slate swan
#

Probably not

#

Having both ctx and inter feels wrong

shrewd apex
#

yeah

#

u cant use callback like that

#

button.callback needs an async function with interaction as first param

#
async def foo(inter):
    ...

button.callback = foo
formal basin
#

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

formal basin
#

oh wait

harsh orbit
#

where I can find all the error like Bad argument, missing permission, etc ..

#

Is there a docs hava all of them?

fickle imp
#

Somebody can help me?
code:
https://paste.pythondiscord.com/JBBQ

error:

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 827, in _do_call
    return await self._callback(self.binding, interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/src/cogs/commands/CompleteOrder.py", line 120, in complete_order
    view.add_item(prev_button.callback(prev_callback))
  File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 324, in add_item
    raise TypeError(f'expected Item not {item.__class__.__name__}')
TypeError: expected Item not coroutine
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'completeorder' raised an exception: TypeError: expected Item not coroutine
/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py:1252: RuntimeWarning: coroutine 'Item.callback' was never awaited
  await self.on_error(interaction, e)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
harsh orbit
#

@shrewd apex

shrewd apex
harsh orbit
#

I want the errors only

harsh orbit
#

Thx

harsh orbit
#
@say.error()
async def say_error(ctx, error):
   if isinstance(error, commands.MissingPermissions):
     await ctx.reply("**Only administrators can use this command")
#

What is coro?

naive briar
#

Coroutine

harsh orbit
#

How I can solve this error

naive briar
harsh orbit
#

Ok

#

I have another question

#
bot.command()
@has_permissions(administrator=True)

Like this it's should only administrators can use it but if I made this

bot.command()
@has_permissions(administrator=True)
@has_role("say")

It's need to be admin and also have the role or only who have the role can use the command without being admins?

shrewd apex
#

both

slate swan
#

Also a good way to answer your own question in your own would be to try it and see

harsh orbit
#

I want only who have the role can use the command and also the admins

#

How?

shrewd apex
#

make a custom check

harsh orbit
#

Didn't understand

naive briar
#

What's confusing about it

harsh orbit
#

Wydm by make a custom check

shrewd apex
#

if u had read a bit of it u would know what to do

harsh orbit
#

Ok

#

That's for errors

#

Not permissions and roles

shrewd apex
#

there is a check part also

#

look at guide

harsh orbit
#

Can you help me now just in this thing

glad cradle
harsh orbit
#

It's only saying how to make has_permission or is_owner etc . Not the answer of my question