#discord-bots

1 messages · Page 698 of 1

eager trail
#

oh i got

heavy folio
#

await message.reply(link.url)

pliant gulch
#

Not here you don't

#

Discord.py internally casts content of Messageable.send to str

heavy folio
#

i remember having this error before though

pliant gulch
#

Invite implements __str__ to return self.url

heavy folio
#

hm

unkempt canyonBOT
#

discord/invite.py lines 433 to 434

def __str__(self) -> str:
    return self.url```
heavy folio
#

oh mb

unkempt canyonBOT
#

discord/abc.py line 1332

content = str(content) if content is not None else None```
final garnet
#

@heavy folio Just ping me once you're ready : )

stray summit
#

!d discord.TextChannel.create_thread

unkempt canyonBOT
#

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

Creates a thread in this text channel.

To create a public thread, you must have [`create_public_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads"). For a private thread, [`create_private_threads`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_private_threads "discord.Permissions.create_private_threads") is needed instead.

New in version 2.0.
eager trail
#

!d discord.TextChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
heavy folio
#

were there any errors btw

lost wolf
#

<@&831776746206265384> one of you dm me i need something important to say

heavy folio
#

just for you to take note you should fix the dict's indents

hollow quarry
lost wolf
#

and its very important

#

i cant

#

i need a mod to add me and dm me

hollow quarry
#

We will not do that, please find a way to DM the bot.

lost wolf
#

i can not do that

hollow quarry
#

Why not?

lost wolf
#

if i turn on dms my messages will get spammed with bots

hollow quarry
#

You only need to turn it on for the length of the conversation.

lost wolf
#

i need to report a user

meager nebula
#

Is there anyway to see your webhooks past message history?

#

Like everything your webhook has said, even in deleted channels?

heavy folio
#

idts

final garnet
# heavy folio just for you to take note you should fix the dict's indents

This should be correct ```py
@client.command() #v1
@commands.has_permissions(kick_members=True)
async def alert(ctx, *, msg):#ALERT

data = {

922874978528034886 : [922875504959295579, 922874978528034888], #Banger Alerts / Server ID, Channel Name, Role ID
884931761610563595 : [921234942405525504, 884974424468623411], #Bangers Den / Low Float
884931761610563595 : [921890822100758528, 884974424468623411], #Bangers Den / Bangers Mid Large
}

for guild_id in data.keys():
    
    guild = discord.utils.get(client.guilds, id=guild_id)
    channel = discord.utils.get(guild.channels, id=data [guild_id][0])
    role = discord.utils.get(guild.roles, id=data [guild_id][1])  
    embed=discord.Embed(title= ':moneybag: **Alert** :moneybag:', description= (msg), color=0x00FF00, timestamp=datetime.datetime.utcnow())
    embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/872295537544679484/922881014852898826/IMG_20211221_001839.jpg')
    embed.set_footer(icon_url = ctx.author.avatar_url, text='Powered by Duck Programming',)
    await channel.send(content=f"{role.mention}")                 
    await channel.send(embed=embed)
heavy folio
#

are there any errors

final garnet
#

Nope

#

No errors at all

#

^^^ this the issue i mean

heavy folio
#

do you have an error handler?

silent portal
#

K got it but it prints out "None" eventho I have a accent color

#

@heavy folio No errors and no error handler. It just prints out "None"

#
@bot.command()
async def mutes(ctx):
    print(ctx.author.accent_color)
final garnet
#

I was thinking is it because how i Loop it?

heavy folio
final garnet
#

Ahh alright ^^

heavy folio
#

it's only loading 1 channel per guild

#

can i know why you need the button btw

#

ButtonStyle.URL doesnt exist, neither does ButtonStyle.url

#

!d discord.ButtonStyle.link

unkempt canyonBOT
final garnet
heavy folio
#

oh alr

final garnet
#

Shit

#

How do I replace that to make it multiple?

heavy folio
#

sorry for the confusion i get what your trying to do now

#

so in the dict, key is guild id, then for the value, there's a list, 1st would be channel id, 2nd would be role id, am i right?

final garnet
#

Yes.

#
    data = {
  922874978528034886 : [922875504959295579, 922874978528034888], #Banger Alerts / Server ID, Channel Name, Role ID
  884931761610563595 : [921234942405525504, 884974424468623411], #Bangers Den / Low Float
  884931761610563595 : [921890822100758528, 884974424468623411], #Bangers Den / Bangers Mid Large
  }
#

For this, Left is GUILD, middle is CHANNELS, right is ROLES

heavy folio
#

alr

#

just tested and it only sent to one channel for me as well, i'll try and find some fix

final garnet
final garnet
pliant gulch
#

That would be why it's only sending in one channel

#

!e ```py
mydict = {"A": 1, "A": 2}
print(mydict["A"])

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

2
quaint epoch
#

hey guys

#

i need help

#

how do i make an on_reaction function that also gets a reaction object, and user/member object?

#

i tried to do this-

#

but it didn't run the event when i reacted

#

so what do i do then?

magic ore
#

look at the note for the event in the docs

#

!d discord.on_reaction_add

unkempt canyonBOT
#

discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.

Note

To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").

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

Note

This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
magic ore
#

Similar to on_message_edit(), if the message is not found in the internal message cache, then this event will not be called. Consider using on_raw_reaction_add() instead

quaint epoch
#

but when i passed user as an argument it just said user is an pos argument that wasn't passed

magic ore
#

look at the docs for the raw event (to see what arguments it takes)

final garnet
pliant gulch
#

Perhaps change the way you store them

#

E.g ```py
data = {guild_id: {channels: [1, 2], roles: [1, 2]}}

#

This way, you just need to access data[guild_id], get iterate through channels and roles

final garnet
#

I wouldn't need these anymore ```py
channel = discord.utils.get(guild.channels, id=data [my_list][0])
role = discord.utils.get(guild.roles, id=data [my_list][1])

pliant gulch
#

Mhm, instead of hardcoding you'd iterate

#

This also means you can send multiple roles now as well

final garnet
#

OHHH

pliant gulch
#

Also consider sending your two messages in one call

#

This saves an API call

#

which is always good,

#

You can just do send(mention, embed=embed)

final garnet
#

so I can just safely remove ```py
await channel.send(content=f"{role.mention}")
await channel.send(embed=embed)

#

and replace it with

send(mention, embed=embed)
pliant gulch
#

Not just send

#

It needs to be called from channel

final garnet
#

await channel.send

pliant gulch
#

Yep

#

Make sure you pass role.mention as well, not just mention it was a placeholder for my example

#

You don't need to f-string it either, mention already returns a string

final garnet
#
        await channel.send(content=f"{role.mention}" ,embed=embed)
final garnet
#
        await channel.send(role.mention, embed=embed)
pliant gulch
#

Yep

final garnet
#

Yep my bad

#

Okay i got derailed from the main problem oops

final garnet
pliant gulch
#

Yes, then iterate through channels, call utils.get etc same as you did earlier, instead of hard coding the index you iterate that is all

final garnet
#
@client.command() #v1
@commands.has_permissions(kick_members=True)
async def alert(ctx, *, msg):#ALERT
    
    data = {922874978528034886: {channel: [921234942405525504, 921890822100758528], roles: {884974424468623411,84974424468623411 }}
            
    for guild_id in data.keys():
        
        guild = discord.utils.get(client.guilds, id=guild_id)
        channel = discord.utils.get(guild.channels, id=data [my_list][0])
        role = discord.utils.get(guild.roles, id=data [my_list][1])  
        embed=discord.Embed(title= ':moneybag: **Alert** :moneybag:', description= (msg), color=0x00FF00, timestamp=datetime.datetime.utcnow())
        embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/872295537544679484/922881014852898826/IMG_20211221_001839.jpg')
        embed.set_footer(icon_url = ctx.author.avatar_url, text='Powered by Duck Programming',)
        await channel.send(role.mention, embed=embed)
#

Something like this right, but i just gotta fix the indentation?

#

@pliant gulch

#

and can u refresh my mind with what iterating is again? I'm sorry I haven't really coded for a few months now. I've been focusing on trading stocks and i wanted to create a bot so i could alert to multiple servers

pliant gulch
#

!e ```py
data = {1: {"channels": [1, 2], "roles": [1, 2]}}
for guild_id, alert_data in data.items():
channels = alert_data["channels"]
roles = alert_data["roles"]

print(guild_id, channels, roles)

silent portal
#

I have 2 on_message events but one of them doesn't work? Like it doesn't react to anything. The other one works fine

unkempt canyonBOT
#

@pliant gulch :white_check_mark: Your eval job has completed with return code 0.

1 [1, 2] [1, 2]
pliant gulch
#

@final garnet CC

#

Now you have the guild_id, the channel ids, and the role ids

#

You then get the guild instance via utils.get

#

Then iterate channels & roles to get their respective objects

#

Then send

final garnet
#

wait let me try it

#

@pliant gulch

@client.command() #v1
@commands.has_permissions(kick_members=True)
async def alert(ctx, *, msg):#ALERT
    
    data = {1: {"channels": [1, 2], "roles": [1, 2]}}
    
    for guild_id, alert_data in data.items():
        channels = alert_data["channels"]
        roles = alert_data["roles"]   
        guild = discord.utils.get(client.guilds, id=guild_id)
        embed=discord.Embed(title= ':moneybag: **Alert** :moneybag:', description= (msg), color=0x00FF00, timestamp=datetime.datetime.utcnow())
        embed.set_thumbnail(url='https://cdn.discordapp.com/attachments/872295537544679484/922881014852898826/IMG_20211221_001839.jpg')
        embed.set_footer(icon_url = ctx.author.avatar_url, text='Powered by Duck Programming',)
        await channel.send(role.mention, embed=embed)
#

Something like this?

pliant gulch
#

No you haven't iterated channels & roles

#

Those are still ints

final garnet
#

Iteration are loops right? SO i can use for loops ? @pliant gulch

pliant gulch
#

yes

final garnet
#
for channels in roles

something like this? @pliant gulch , working on it

slate swan
#

I’m making a help command, but when the user mentions the bot, it sends it in dms but it’s not working can I have help


@commands.Cog.listener()
    async def on_message(self, message):
        if self.client.user.mentioned_in(message):
            await message.channel.send(MyHelp)```
final garnet
#

!e

for number in range(6):
    print(number)
unkempt canyonBOT
#

@final garnet :white_check_mark: Your eval job has completed with return code 0.

001 | 0
002 | 1
003 | 2
004 | 3
005 | 4
006 | 5
final garnet
#

@pliant gulch Not defined?

slate swan
#

then define channel

final garnet
#

I'm kinda embarassed with myself rn for tonight, The knowledge I used to have isn't rolling in

heavy folio
#

also what i understand here is if someone mentions the bot, it'll send the help command? in dms or in the channel

slate swan
heavy folio
slate swan
#

Yeah

heavy folio
#

yeah because you cant just send a class peepobigsmile

slate swan
#

That’s what I want it to do

heavy folio
#

!d discord.ext.commands.Bot.get_context

unkempt canyonBOT
#

await get_context(message, *, cls=<class 'discord.ext.commands.context.Context'>)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Returns the invocation context from the message.

This is a more low-level counter-part for [`process_commands()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.process_commands "discord.ext.commands.Bot.process_commands") to allow users more fine grained control over the processing.

The returned context is not guaranteed to be a valid invocation context, [`Context.valid`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context.valid "discord.ext.commands.Context.valid") must be checked to make sure it is. If the context is not valid then it is not a valid candidate to be invoked under [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
heavy folio
#

use this to get context, py ctx = await bot.get_context(message)then ```py
await ctx.send_help()

slate swan
#

Oh

slate swan
#

Ok it works

#

How do I make it send to dm?

#

@heavy folio

heavy folio
slate swan
#

Sorry for the ping py_guido

heavy folio
#

not sure bout that

slate swan
#

Oh

tacit storm
#

first of all

#

you can do it like that

boreal ravine
#

?

slate swan
#

don't see anything wrong there

tacit storm
#

the easiest way to do

#

is by calling it in your async

#

like so

boreal ravine
#

he is though?

heavy folio
#

?????

slate swan
#

it will excluded all the checks you have in your help command

tacit storm
#

every single discord.py bot ive seen, calls ctx in the async.

heavy folio
#

sigh

tacit storm
#

not with a variable

boreal ravine
#

lmao.

slate swan
#

It's an on_message event.......

heavy folio
#

why'd i be dumb enough to use get_context if i can pass ctx as a param in the func

slate swan
#

I don't even know why I get this lol , no idea what bot they are talking about

tacit storm
heavy folio
#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
heavy folio
#

now tell me where the ctx comes from

boreal ravine
#

@slate swan clear your pings pls 🙏

tacit storm
#

thats my bad.

nocturne saddle
#

lmfao

slate swan
tacit storm
heavy folio
#

if it's a command i wont even touch get_context peepobigsmile

nocturne saddle
boreal ravine
tacit storm
manic wing
heavy folio
#

stop line splitting btw

tacit storm
boreal ravine
#

chill out, you dont wanna get muted like the last guy 💀

tacit storm
manic wing
#

!d discord.Member.avatar

unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
pliant gulch
silent portal
#

How can I get a WHOLE file's text?

humble sorrel
#

hi

slate swan
#

if its a txt file , read/readlines will be enough

boreal ravine
slate swan
#

waits for "but its for a discord bot"

silent portal
#

oh yh ur right

#

but thank you

pliant gulch
loud junco
#

how to add hyperlink on embed footer

slate swan
#

i dont think you can hyperlink in footers

loud junco
#

:/

#

ok

#

then imma just hyperlink in a field

final garnet
#

!e
for guild_id, alert_data in data.items():

channels = alert_data[channels[0]                
roles = alert_data[roles[1]   
guild = discord.utils.get(client.guilds, id=guild_id)

print(channels)

unkempt canyonBOT
#

@final garnet :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 3
002 |     channels = alert_data[channels[0]                
003 |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
final garnet
#

!e
for guild_id, alert_data in data.items():

channels = alert_data[channels[0]                
roles = alert_data[roles[1]]   
guild = discord.utils.get(client.guilds, id=guild_id)

print(channels)

unkempt canyonBOT
#

@final garnet :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 3
002 |     channels = alert_data[channels[0]                
003 |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^
004 | SyntaxError: invalid syntax. Perhaps you forgot a comma?
boreal ravine
#

@final garnet #bot-commands bruh

final garnet
#

oh shi

cobalt jacinth
#
if not message.author.bot:
    return
if "hello" in  message.content :
    await message.channel.send(message.content)
else:
    return
boreal ravine
#

why return

cobalt jacinth
#

guys this makes bot the start spamming hello

boreal ravine
#

then try again

cobalt jacinth
#

i want it only respond if the message sent by a webhook

boreal ravine
#

the if statement will proceed if the condition was true, message.author.bot was true

cobalt jacinth
#

how do i do that

boreal ravine
#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.webhooks "discord.Guild.webhooks") and [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.7)"):
slate swan
#

yo kale

boreal ravine
#

yo acey

slate swan
#

can i have some kale?

boreal ravine
#

im out of kale

slate swan
#

;-;

final iron
cobalt jacinth
#
if message.webhook_id:
        if "hello" in  message.content :
            await message.channel.send(message.content)
#

is this correct ?

boreal ravine
#

i guess

cobalt jacinth
#

ok thx

boreal ravine
#
if ... == discord.Webhook:
    ...
pliant gulch
#

How would this even work?

cobalt jacinth
#

the webhook link can be anything

boreal ravine
pliant gulch
#

Where would you get the web hook instance firstly, secondly that syntax isn't right

boreal ravine
#

whats wrong in the syntax?

#

mb

pliant gulch
#

And how does this even allow for you to check if a message was from the webhook?

boreal ravine
pliant gulch
#

Message.author will be a webhook instance???

#

🤔

#

Also fourthly that's not how you check if a object is a type of object

#

You'd use isinstance

slate swan
#

it will be a User obj

pliant gulch
#

The best way to check here is via webhook_id

boreal ravine
#

check if its a user then? i havent even confirmed this yet and obviously sarthak did

pliant gulch
#

Why are you giving information that you didn't even bothered to check then

boreal ravine
#

i wouldnt have time to check even

pliant gulch
#

Yikes, why did you suggest this in the first place then

#

👁️👄👁️

boreal ravine
#

because they needed help

pliant gulch
#

And then you decided to give false information and correct on them when they were doing the right thing in the first place

#

Great help

boreal ravine
#

¯\_(ツ)_/¯

cobalt jacinth
#

is it ok to check for the guild id in sqlite databse inside on_message function ? its gonna query the database everytime somebody send some message in the server

#

can sqlite handle it ?

pliant gulch
#

Yes it can very much handle that

#

Databases are meant to be queried a lot /can be

#

If you want to save resources you can also cache the database

cobalt jacinth
#

i am thinking of querying the database after checking if the message is a webhook and it contains what i want...that cut the queries by a lot.

cobalt jacinth
pliant gulch
#

Basically just make a dict, inside of your on_message check if the guild’s id is inside of the dict if it is return that else query the database, add a new key value pair (guild id, data) to the dict

#

Now any future on_messages from the guild have the data cached and can just return that

#

You just need to make sure you update the cache everytime you make an operation on the database that modifies the corresponding data so that is it “up to date”

cobalt jacinth
#

ohhh

#

i did that once..didnt know its called caching

#

thx

pliant gulch
#

👍

silent portal
#

Is there a bool to check if an invite is valid?

cobalt jacinth
#

channel = discord.utils.get(bot.get_all_channels(), name="title-status")
its not working for me...its mixing differnt servers

silent portal
#

Then define your Guild

torn sail
#

Do guild.channels or something

cobalt jacinth
#
@bot.listen()
async def on_message(message):
    if not message.webhook_id:
        return
    if "hello" in  message.content :
        channel = discord.utils.get(bot.get_all_channels(), name="title-status")
        await channel.send(message.content)
#
channel = discord.utils.get(bot.guild.get_all_channels(), name="title-status")
#

like this ?

torn sail
#

So what r u trying to do

cobalt jacinth
#

if there is a webhook with message hello comes in the server...send that webhook to channel named title-status

torn sail
#

And what’s happening?

cobalt jacinth
#

its mixing all servers

torn sail
#

Could you rephrase that? I don’t really understand

#

Is it sending in multiple servers?

cobalt jacinth
#

it detects message from other servers and send that message to channel names title-status

#

discord.utils.get(message.guild.get_all_channels(), name="title-status")

#

is it correct ?

torn sail
#

Is the channel in a specific guild?

cobalt jacinth
#

it should be in every guild

slate swan
torn sail
#

^^^

cobalt jacinth
#

discord.utils.get(message.guild.channels(), name="title-status")

#

right ?

slate swan
#

no

torn sail
#

Take out the parenthesis after channels

slate swan
#

its a property . not a method remove the braces

cobalt jacinth
#

okok

#

ok works...thx all

slate swan
#

pleasure

cobalt jacinth
#

user = get(bot.get_all_members(), id="1234")
is this correct way to get a username by its id

slate swan
#

if you have id , just use bot.get_user(id).name

cobalt jacinth
#

ok thx

torn sail
#

Ummm how is that related to discord bots

sick birch
#

get_* methods are O(1) while utils.get is much much slower

#

it's also unwieldy and frankly unnecessary

pliant gulch
#

All get_ methods are O(n) not all but a decent chunk*

#

I'll check again it might not be all but I do remember most of them being

bright palm
#

Pretty sure they are O(1) cause they are just getting something out of a dictionary

pliant gulch
#

Checked get_guild get_emoji get_member get_user are O(1)

#

Just checked some more they are O(n)

#

I do remember somewhere about people saying how most get_ methods are O(n)

bright palm
#

And get_stage_instance

pliant gulch
#

Kinda weird how some of them are O(n) when they could be O(1)

bright palm
pliant gulch
#

I was checking the pre 2.0 docs so I missed out on those

pliant gulch
unkempt canyonBOT
#

discord/state.py lines 1381 to 1393

def get_channel(self, id: Optional[int]) -> Optional[Union[Channel, Thread]]:
    if id is None:
        return None

    pm = self._get_private_channel(id)
    if pm is not None:
        return pm

    for guild in self.guilds:
        channel = guild._resolve_channel(id)
        if channel is not None:
            return channel```
pliant gulch
#

This could be easily O(1)

#

As in discord you don't need the guild's id which the channel is present in

#

You just access via discord.com/api/v9/channels/channel_id

#

You should be able to just store a global cache of channels

pliant gulch
pliant gulch
#

The bot uses the github API

boreal ravine
#

hm

arctic gyro
#

Hi
is there any code for the new timeout feature ?

boreal ravine
#

disnake/pycord has it

arctic gyro
#

so would await ctx.guild.timeout work?

slate swan
#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
boreal ravine
stuck parrot
#

hi

#
import discord
from discord.ext import commands
import asyncio


a=0
class MyClient(discord.Client):
  
    def 

__init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # create the background task and run it in the background
        self.bg_task = self.loop.create_task(self.my_background_task())


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


    async def my_background_task(self):
        
        await self.wait_until_ready()
        
    
        channel = self.get_channel(12222222111) 
        while not self.is_closed():
            # counter += 2
           
           await channel.send( a) 
         
           await asyncio.sleep(2) # task runs every 60 seconds
           #stop sending messages after 10 messages

client = MyClient()


for i in range (0,10):
    client = MyClient()
    client.loop.create_task(client.my_background_task(i))
    client.run('xxxxxxxxxxxxxxx')
#

Hi, I'm trying to sent a message with the value of i to a discord chanel, but I don't know why isn't working

quick gust
#

is that even a valid channel ID

stuck parrot
torn sail
#

R u getting any errors

stuck parrot
#

yes

torn sail
#

What errors?

outer violet
#

How do I make this send to dm and respond with “you’ve got mail!” or something in the channel?

@commands.Cog.listener()
    async def on_message(self, message):
        ctx = await self.client.get_context(message)
        if self.client.user.mentioned_in(message):
            await ctx.send_help()```
torn sail
#

ctx.author.send and ctx.send?

stuck parrot
torn sail
#

What line?

stuck parrot
#

20

torn sail
#

Can u write the code for the line. I’m on my phone so I can’t see the code well

stuck parrot
#

I see

torn sail
#

Or maybe take a screenshot

#

That would help

stuck parrot
#

just a sec

torn sail
#

Can you screenshot the error @stuck parrot

boreal ravine
arctic gyro
torn sail
boreal ravine
#

it requires an argument

stuck parrot
boreal ravine
slate swan
#

since discord wants every verified dev to have slash commands in his bot and discord.py doesnt supports slash commands is there any other library where I can combine dpy and add slash commands in my bot?

boreal ravine
#

you know how to call a function but not pass args to one

torn sail
boreal ravine
stuck parrot
#

can you pls pass me an example??

boreal ravine
#

no

#

basic python

torn sail
#

@stuck parrot so u have a required arguement in my_backgrounf_task. In the def init ur calling it without passing in the arguement

boreal ravine
#

typos

torn sail
stuck parrot
slate swan
#

Btw which intent for on_guild_channel_delete event . Anyhelp?

visual island
#

guild intents

rapid walrus
#
import pyautogui
from win32 import win32gui
import discord
import requests

def screenshot(window_title=None):
    if window_title:
        hwnd = win32gui.FindWindow(None, window_title)
        if hwnd:
            win32gui.SetForegroundWindow(hwnd)
            x, y, x1, y1 = win32gui.GetClientRect(hwnd)
            x, y = win32gui.ClientToScreen(hwnd, (x, y))
            x1, y1 = win32gui.ClientToScreen(hwnd, (x1 - x, y1 - y))
            im = pyautogui.screenshot(region=(x, y, x1, y1))
            return im
        else:
            print('Window not found!')
    else:
        im = pyautogui.screenshot()
        return im


im = screenshot('Calculator')
if im:
    webhook = discord.Webhook.partial(123456, 'hide for now', adapter=discord.RequestsWebhookAdapter())
    webhook.send('HOHO IT WORKS!', file=im)
#

help me ;-;

#

😐

maiden fable
#

It's not a dpy error

rapid walrus
#

??

#

ye

maiden fable
obsidian ledge
#

how to use the new timeout thingy

boreal ravine
#

skeppy

boreal ravine
obsidian ledge
#

nextcord

#

i meant pycord

devout helm
#

hi i was trying to get my bot verified and i get this error:

#

any solutions?

slate swan
#

did you enter something in the bot description?

devout helm
#

yes

#

changed it multiple times but it still shows this error

gaunt ice
#

what's the description

devout helm
#

nvm, it got resolved after i changed it now

gaunt ice
#

oof

tough lance
#

Oof

boreal ravine
#

How do I check if a member has an avatar or not

gaunt ice
#

um

#

wdym

boreal ravine
#

didnt i say it clearly enough tho

#

i wanna check

#

if a member

#

has an avatar or not

gaunt ice
#

every member has a avatar

boreal ravine
#

no

gaunt ice
#

u mean the

boreal ravine
#

i wanna check if they have the default one

gaunt ice
#

defaultdiscord pfp?

boreal ravine
#

thats considered no avatar

gaunt ice
#

hmm oki wait

boreal ravine
gaunt ice
#

u need to have all the default images

#

and

#

wait

boreal ravine
#

isnt there a better way

#

to do what i want instead of that

spring flax
#

how do i timeout a member in disnake?

boreal ravine
unkempt canyonBOT
#

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

Edits the member’s data.

Depending on the parameter passed, this requires different permissions listed below...
boreal ravine
#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
spring flax
#

i put await member.timeout(**args) but it said member object has no attr timeout

boreal ravine
#

you can use the method

boreal ravine
#

its supposed to be 2.3

night berry
#

is it possible to make a discord activities command in python

spring flax
#

ah i have 2.2.2

#

my bad thanks

boreal ravine
#

lmao

night berry
#

or do i have to use another package

boreal ravine
#

uh you could use raw requests

#

!d discord.VoiceChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
boreal ravine
night berry
#

ty

boreal ravine
#

it has like 2 kwargs for making an activity

#

im not sure how to use it though, looks like you'd have to get the application id

candid pier
#

!d disnake.Member

unkempt canyonBOT
#

class disnake.Member```
Represents a Discord member to a [`Guild`](https://docs.disnake.dev/en/latest/api.html#disnake.Guild "disnake.Guild").

This implements a lot of the functionality of [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://docs.disnake.dev/en/latest/api.html#disnake.User "disnake.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
obsidian ledge
#

how to use the new timeout thing

boreal ravine
#

didnt you ask this earlier?

#

o

boreal ravine
#

you can use that to timeout someone

obsidian ledge
#

alright, thank you

snow flare
#

Do interactions only last for 5 seconds? Or am I stupid?

visual island
#

15 minutes

snow flare
#

well, for some reason some of my interactions only seem to work for 3 seconds

#

even if the user has interacted with it in the first three seconds, he can't interact with it again

visual island
#

show code

visual island
sinful pasture
#

Is timeout basically user.timeout or is it different?

visual island
#

member.timeout(...) yes

sinful pasture
#

Oh right member

snow flare
#

alright, let me see if I can fix it

sinful pasture
visual island
#

await member.timeout(duration=10) or await member.timeout(until=datetime.datetime(...))

sinful pasture
#

thanks!

snow flare
#

btw, what if I have a ticket support system thingy, will I have to send out a new panel every 15 minutes, because the interaction token supposedly times out?
Or will it be fine, and would still work forever, as long as the bot is online?
@visual island

visual island
#

if you're doing it somewhere else then no

snow flare
#

what do you mean by somewhere else?

#

How does the ticket tool bot work then?

visual island
#

like,

async def my_other_callback_that_will_work_forever(self):
  while True:
    # do stuff

async def callback(self, ...):
  # do stuff
  await self.my_other_callback_that_will_work_forever()
```probably?
#

i've never seen what ticket tool really does, but iirc they use reactions instead of buttons?

snow flare
#

nah, they use buttons now

#

they changed reactions to buttons

visual island
#

hmm wait

#

you really need interaction tokens for everything tho

snow flare
#

yeah, alright, thanks, I'll try to research it more

shadow wraith
#

why doesn't this trigger the if statement?

@ bot.command()
@ commands.guild_only()
async def report(ctx: commands.Context, member: discord.Member, *, reason):
    if member.roles in ['staff', 'Bot Developer']:
        await ctx.reply("You cannot report a staff or the bot developer itself :mikebruh:")
    else:
        await bot.get_channel(921048882346078279).send("{} has been reported for {} by {}".format(member, reason, ctx.author))
        reportSuccess = await ctx.send("Yo! Your report was sucessfully send to the staff of this server, we will get it reviewed.")
snow flare
cobalt jacinth
#

is it possible to
first send a normal message msg = ctx.send("hello")
then edit it and add embed msg.edit(embed = myembed)

quick gust
#

yes it is

cobalt jacinth
#

ok thnx i will give it a go then

visual island
unkempt canyonBOT
#

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

Defers the interaction response.

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

is hex code usable in embed ? #33CCCC this

shadow wraith
velvet tinsel
#

or you can try for roles in member.roles

#

and if role in [...]

shadow wraith
#

yeah that's a good idea

#

don't think for loops would work though but alright

velvet tinsel
#

I hope it works

shadow wraith
#

ok but what could role be defined as

#

because i think you misread my command, or does it just need a definition

cobalt jacinth
shadow wraith
cobalt jacinth
#

how to remove this adding

cobalt jacinth
shadow wraith
#

do content="" at your .edit

cobalt jacinth
shadow wraith
#

can't confirm if it works though

shadow wraith
#

oh i get what im meant to define role as now

snow flare
#

and then put it into some while loop or something

visual island
#

that doesn't exist in dpy

#

but if you're using other lib then yeah

shadow wraith
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
shadow wraith
#

@visual island 🧢

visual island
#

what?

#

button_click event doesn't exist

shadow wraith
#

oh

#

im pretty sure on_button_click exists tho

#

nope it doesn't fuck

cobalt jacinth
#

can it be moved at the end ?

#

it creates this ugly gap

snow flare
shadow wraith
snow flare
slate swan
#

!d discord.ext.commands.Bot.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
shadow wraith
#

because i need help

cobalt jacinth
snow flare
boreal ravine
#

40 minutes

tough lance
#

Lmao

zealous dagger
#

hey can someone tell if I want to take multiple commands

#

how do I do that

hexed timber
#

If I need to store stuff in a json file for instance { "name" : ctx.author "id" : ctx.author.id } Why does it say its not serialized

#

@zealous dagger What do you mean take multip[le commands?

zealous dagger
#

Means like

#

I am making a pammer

#

spammer bot

#

which spams

#

so I want that

#

If should take commands like this

#

s!spam "This is a spam message" 60

hexed timber
#

like multiple command line arguements?

zealous dagger
#

s!spam starting command

#

And the quote is the message

#

and 60 is the number of times

#

that should be spammed

#

@hexed timber

hexed timber
#

Youll have async def spam(ctx, args1, arg2, args3) Where args1 will be spam args2 will be the message and args3 will be the time

zealous dagger
#

Ok

hexed timber
#

just pass in multiple variable to the async function

zealous dagger
#

Can you send a snippet

#

FOr bettter undertsanding

#

@hexed timber

#

I mean a sample code

hexed timber
#

That is the snippit above

zealous dagger
#

Ok

#

Thanks

hexed timber
#

if you print args1 that will print spam if you print args2 it will print the quote and if you print args3 it will pring the time

zealous dagger
#

Ok

slate swan
shadow wraith
#

i tried with ids 🚎

placid skiff
#
    
async def on_guild_update(self, before: Guild, after: Guild):
        if before.name != after.name:
            db.execute("UPDATE Guild SET Name = ? WHERE GuildID IS ?", after.id, after.name)
            db.commit()

Guys I have this function here inside a Cog which is supposed to be called when a guild update but nothing happens, why?

shadow wraith
#

still didn't work

slate swan
placid skiff
shadow wraith
#

atleast thats what i think

#

im getting no tracebacks btw

hexed timber
#

make a variable that contains the list of role names then check if one of the roles is in the list then also check if the other role is in the list

#

@shadow wraith do you have any error handling?

placid skiff
#

no no you are doing like this:

lst1=[1,2]
lst2=[2,3]
if lst1 in lst2:
  #something
#

member.roles is the list of all roles that a member has

shadow wraith
#

!e

list1 = [1, 2]
list2 = [3, 2]
if list1 in list2:
  print("works?")
unkempt canyonBOT
#

@shadow wraith :warning: Your eval job has completed with return code 0.

[No output]
placid skiff
#

see? xD

shadow wraith
#

didn't i add an else statement?

hexed timber
#

shouldent it be something like roles = [role1, role2] if(role1 in role or role2 in role)

placid skiff
#

you can check if a variable is in a list but not if a list is in a list

placid skiff
shadow wraith
#

!e

list1 = [1, 2]
list2 = [3, 2]
for item in list1:
  if item in list2:
    print("test?")
hexed timber
#

I got no clue for that one bruv

unkempt canyonBOT
#

@shadow wraith :white_check_mark: Your eval job has completed with return code 0.

test?
shadow wraith
#

huh so for loop would be working in this case

placid skiff
velvet tinsel
shadow wraith
# velvet tinsel what's wrong

no i fucking figured out something 💀 btw what happened to js in python you havent coded in that repl for a while

placid skiff
#

It is loaded bro...

shadow wraith
slate swan
velvet tinsel
#

thank you sarthak

#

🙂

velvet tinsel
hexed timber
#

@velvet tinsel ```Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/usr/local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type Member is not JSON serializable

        "name" : ctx.author,
        "id" : ctx.author.id,
        "money" : 0
    }
    print(my_json)```
placid skiff
# velvet tinsel thank you sarthak
Running setup...
    loadin general
    general loaded
    loadin test
    test loaded
running bot...
bot connected
        general ready
        test ready
Bot ready

See? when i run the bot i have this function that tells me if the cogs i have are loaded or they have some error, the coge in that function is general

slate swan
placid skiff
velvet tinsel
slate swan
hexed timber
#

I still get an error when I tried that

#

I looked at the overflow already

#

can I not serialize it the way im doing it?

placid skiff
velvet tinsel
#

what's the full code

velvet tinsel
placid skiff
#

Lol where? xD

#

oh xD

#

my bad

slate swan
placid skiff
slate swan
hexed timber
#

@slate swan my_json = { "name" : str(ctx.author), "id" : str(ctx.author.id), "money" : str(0) } print(my_json) Like this?

slate swan
placid skiff
#

i'll add it again

slate swan
# placid skiff i tried with it too lol same thing

Apply the decorator , and in the code change py db.execute("UPDATE Guild SET Name = ? WHERE GuildID IS ?", after.id, after.name) to

db.execute("UPDATE Guild SET Name = ? WHERE GuildID IS ?", (after.name , after.id))```
shadow wraith
#

tried using a for loop

role = [912631582681092117, 914534709986467890]
    for item in member.roles:
        if role in member.roles:
            await ctx.reply("You cannot report staff :mikebruh:")
            break
        else:
            h = bot.get_channel(921048882346078279)
            await h.send("{} has been reported for {} by {}".format(
                member, reason, ctx.author))
            await ctx.send("Yo! Your report was sucessfully send to the staff of this server, we will get it reviewed.")
            break
#

apparently, you can still report peopple with the roles, the if statement cannot and will not be triggered for some reason :c

placid skiff
shadow wraith
slate swan
velvet tinsel
velvet tinsel
placid skiff
#
def execute(command, *values):
    cur.execute(command, tuple(values))
#

This is the execute script, it turns my values into a tuple

slate swan
#

Ah okok

#

Well the order is still wrong

placid skiff
#

so it is not that, as i said the on_guild_update doesn't even run

boreal ravine
placid skiff
boreal ravine
#

!e
def b(*x): return x
print(b(1))

unkempt canyonBOT
#

@boreal ravine :white_check_mark: Your eval job has completed with return code 0.

(1,)
slate swan
boreal ravine
#

whats the point of casting it

slate swan
#

They are enabled by default

placid skiff
placid skiff
shadow wraith
placid skiff
#

but why in the debug i haven't never seen it step up into the function?

shadow wraith
#

unless your talking about that list

velvet tinsel
unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
boreal ravine
shadow wraith
boreal ravine
#

im not asking for help

velvet tinsel
#

lmao I know

slate swan
#

!e py for meh in [1,2,3]: print meh is what I'm doing

velvet tinsel
#

it looks ugly if you don't use ```

slate swan
#

Um

#

Ah f

velvet tinsel
slate swan
#

Kill me already

boreal ravine
#

<@&831776746206265384> ban!!

slate swan
#

shipit What role is that?

shadow wraith
#

did you just fail to joke ping mods?

boreal ravine
#

yes

slate swan
#

Nah , edits don't actually ping a role/user

boreal ravine
#

^

shadow wraith
#

lma

upbeat otter
slate swan
#

I thought it was the GuildID , to ping everyone

velvet tinsel
slate swan
shadow wraith
upbeat otter
slate swan
#

Ofc

upbeat otter
shadow wraith
#

it's almost night (not in my native country rn 💀)

upbeat otter
slate swan
#

for me it's 5:08 pm

shadow wraith
upbeat otter
unkempt canyonBOT
slate swan
#

yeah NVM me

maiden fable
#

who's fronto now stare

tawdry perch
#
    @commands.command()
    async def to(self, ctx, member: disnake.Member, duration: int, reason: str = None):
        if reason is None:
            reason = "You have been timed out from guild due to moderation actions."
        await member.timeout(duration)  
        await ctx.send("Working")
``` I tried passing a reason as well but it did not work. error: https://paste.pythondiscord.com/xaqesanoya.sql
slate swan
#

timeout(duration=duration)

#

It's a kwarg

tawdry perch
#

oh

velvet tinsel
#

oh

tawdry perch
#

thx! it worked, now I just need to get the correct perms

tawdry perch
#

¯_(ツ)_/¯

#

maybe a float to be exact

velvet tinsel
#

naw it was a member.timeout mistake

#

silly cyberweapon 🚶‍♂️

slate swan
#

float or event a datetime object would work ,with until= datetime

tawdry perch
#

works with int*

#

now I have working timeout system!

#

Maybe I need to add some db logs to it sadly

velvet tinsel
#

cool

#

gl

slate swan
#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
boreal ravine
#

ok

#

hm

slate swan
boreal ravine
#

so the other kwarg in the edit method takes a datetime.datetime object? or am i missing something

tawdry perch
#

disnake docs are supported by python?!

slate swan
#

can take both an int and a datetime object

boreal ravine
#

o

slate swan
boreal ravine
slate swan
#

nextcord's too

tawdry perch
#

oo

slate swan
#

!d

unkempt canyonBOT
slate swan
#

not pycord tho because it's a shit lib that no one should use Pepe_Laugh

tawdry perch
#

Does this message look good or should it be smth else?

boreal ravine
tawdry perch
#

oh I must add duration to message

slate swan
#

kinda sucks how timeouts only work up to 28 days, reason why i'll keep using the mute i was using until now ASakashrug

tawdry perch
#

I will use both features, for short mutes and stuff I think timeout is good, but longer ones should be handled by muted role

velvet tinsel
quick gust
velvet tinsel
quick gust
velvet tinsel
quick gust
#

why are you so offended lmao

velvet tinsel
#

naww I was joking lmao

quick gust
#

.

velvet tinsel
#

anyways we are getting a little bit off-topic let's talk about discord bots before minaberry kicks us out

boreal ravine
#

.catify

velvet tinsel
#

?

#

wtf 😂

slate swan
#

.catify

boreal ravine
#

do it

#

fuck

sinful pasture
#
await member.timeout(duration=10)

Member has no attribute timeout

#

help

slate swan
velvet tinsel
#

lib 🙂

sinful pasture
#

what do I need to use?

slate swan
#

disnake, latest version

velvet tinsel
#

what are you using?

slate swan
#

Disnake v 2.2.3

placid skiff
sinful pasture
#

so i need to import disnake?

slate swan
sinful pasture
#

i was using discord ;-;

slate swan
#

Oh

slate swan
sinful pasture
#

yeah

slate swan
sinful pasture
slate swan
#

you ain't gonna get anywhere if you don't switch because of that ASakashrug

quick gust
velvet tinsel
#

!e

from random import choice

class Cat:
  def catify(self):
    cats = ["fat cat", "short cat", "long cat", "pop cat", "thin cat"]
    return choice(cats)

kraots = Cat()
kraots.catify()
print(kraots)
quick gust
velvet tinsel
#

shit

tawdry perch
#

How can I get path to those cogs folder? ```py
───MyBot
│ ├───cogs
│ │ ├───moderation
│ │ │
│ │ ├───other

slate swan
unkempt canyonBOT
#

@velvet tinsel :white_check_mark: Your eval job has completed with return code 0.

<__main__.Cat object at 0x7f9d72147c10>
velvet tinsel
#

ah

slate swan
#

Mhm

tawdry perch
placid skiff
#

you can use glob or other package to get all files from the directory which has the .py extension

tawdry perch
#

files? I have to get the folder after cogs

placid skiff
#

So you have other folders inside your cogs folder?

tawdry perch
#

yes,

placid skiff
#

and in that folder there are other cogs?

#

or simple scripts?

tawdry perch
#

some cogs are in folder cogs others are in those 2 folders, moderation/other

placid skiff
#

yeah but that says nothing lol
if you have other cogs in that folder inside your cogs folder then you have to load them from that folder

#

ok so you need a script which read everything inside the cogs folder and then if it finds another folder, get in it and then read the name of the cogs and load it from that folder path

tawdry perch
#
my_command = self.bot.get_command(command)
``` I got the command, but how do I get the cogs folder name it is in
placid skiff
visual island
tawdry perch
visual island
#

yeah use that

placid skiff
tawdry perch
visual island
#

yes

tawdry perch
#

oo

boreal ravine
#

!d discord.ext.commands.Command.cog

unkempt canyonBOT
boreal ravine
placid skiff
visual island
#

it gets the cog class not cog folder

placid skiff
visual island
placid skiff
tawdry perch
#

oh thx I'll try them out

tawdry perch
visual island
tawdry perch
#

oh..

wide tartan
#

I'm trying to get the category part in the help command to work, but seems like it doesnt

stark geyser
#

why wont it let me import client from discord.ext ?

wide tartan
#

actually wait

#

it's because

#

you need to change it to this:

minor ether
#

how does the timeout command work?

wide tartan
#

from discord import client

minor ether
#

what does the until argument take

tawdry perch
#

!d disnake.Member.timeout

unkempt canyonBOT
#

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

Times out the member from the guild; until then, the member will not be able to interact with the guild.

Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.

You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.

New in version 2.3.
minor ether
#

so there's duration also huh

tawdry perch
#

Ye

minor ether
#

that's better then

#

until seems a bit confusing

tawdry perch
#

It's just a datetime obj

minor ether
#

new to datetime but what input do you give for the until argument? 🤨

tawdry perch
#

You give it a datetime obj, the docs explains it better
For duration you give a int or a float

minor ether
#

oh so you say time out someone until say 5:30?

tawdry perch
#

If it's a datetime obj it would work

minor ether
#

appreciate it man thanks

tawdry perch
#

Np, gl

placid skiff
minor ether
#

what docs are you saying

placid skiff
#

Oh no my bad

#

It is union of timedelta and float

minor ether
#

i dont see that here for some reason 🤨

tawdry perch
#

See what?

minor ether
#

duration

placid skiff
tawdry perch
minor ether
#

and duration takes in seconds?

tawdry perch
#

Ye, you can pass for example 10 and it means 10 seconds timeout

minor ether
#

Thanks

stark geyser
#

class Commands(client.Cog):
AttributeError: module 'discord.client' has no attribute 'Cog'

#

dont know whats wrong

slate swan
#

!d discord.ext.commands.Cog

unkempt canyonBOT
#

class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.

A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.

When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
slate swan
#

It's not a part of Client

#
@bot.command(help="Play with .rps [your choice]")
async def rps(ctx):
    rpsGame = ['rock', 'paper', 'scissors']
    await ctx.send(f"Rock, paper, or scissors? Choose wisely...")

    def check(msg):
        return msg.author == ctx.author and msg.content.lower() in rpsGame

    user_choice = await bot.wait_for('message', check=check)

    comp_choice = random.choice(rpsGame)
    if user_choice == 'rock':
        if comp_choice == 'rock':
            await ctx.send(f'Well, that was weird. We tied.\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Nice try, but I won that time!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Aw, you beat me. It won't happen again!\nYour choice: {user_choice}\nMy choice: {comp_choice}")

    elif user_choice == 'paper':
        if comp_choice == 'rock':
            await ctx.send(f'The pen beats the sword? More like the paper beats the rock!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Oh, wacky. We just tied. I call a rematch!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Aw man, you actually managed to beat me.\nYour choice: {user_choice}\nMy choice: {comp_choice}")

    elif user_choice == 'scissors':
        if comp_choice == 'rock':
            await ctx.send(f'HAHA!! I JUST CRUSHED YOU!! I rock!!\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'paper':
            await ctx.send(f'Bruh. >: |\nYour choice: {user_choice}\nMy choice: {comp_choice}')
        elif comp_choice == 'scissors':
            await ctx.send(f"Oh well, we tied.\nYour choice: {user_choice}\nMy choice: {comp_choice}")

command does not respond to rock, scissors or paper

visual island
tawdry perch
#

I alrd did

tawdry perch
#

Output was C:\Users\nipa\projects\project\MyBot\cogs\moderation\admins.py

slate swan
#
  File "main.py", line 286, in on_message
    await client.change_presence(status=discord.Status.do_not_disturb, activity=activity)
  File "/home/sami/.local/lib/python3.7/site-packages/discord/client.py", line 1062, in change_presence
    await self.ws.change_presence(activity=activity, status=status, afk=afk)
  File "/home/sami/.local/lib/python3.7/site-packages/discord/gateway.py", line 625, in change_presence
    await self.send(sent)
  File "/home/sami/.local/lib/python3.7/site-packages/discord/gateway.py", line 587, in send
    await self.socket.send_str(data)
  File "/home/sami/.local/lib/python3.7/site-packages/aiohttp/client_ws.py", line 150, in send_str
    await self._writer.send(data, binary=False, compress=compress)
  File "/home/sami/.local/lib/python3.7/site-packages/aiohttp/http_websocket.py", line 687, in send
    await self._send_frame(message, WSMsgType.TEXT, compress)
  File "/home/sami/.local/lib/python3.7/site-packages/aiohttp/http_websocket.py", line 598, in _send_frame
    raise ConnectionResetError("Cannot write to closing transport")
ConnectionResetError: Cannot write to closing transport
#

Bot is offline

cold sonnet
#
    await client.change_presence(status=discord.Status.do_not_disturb, activity=activity)```
?
slate swan
#

*Not started yet

#

Ow

cold sonnet
#

what you did there seems weird

slate swan
#

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

here all functions, removed imports, variables and token

cold sonnet
#

you are changing your status on every message?

visual island
#

you're sending to many requests, dpy ratelimit handler cant handle that much request

slate swan
#

ah

cold sonnet
#

and that bot is... weird in many ways bro

#

that's not normal

slate swan
#

its

#

!= very normal

cold sonnet
#

actually you are changing your status on every message 2 times

slate swan
#

hm yeah

#

and its sending a message every second

little ether
cold sonnet
#

bro what the f

#

you are sending a message every second

#

that's api spamming

cold sonnet
#

and you change your status

#

2 times/s

slate swan
#

and I like to speed it up sometimes by running the code on 2 diff servers

cold sonnet
#

well no wonder discord hates that bot

slate swan
#

damn its on 65 servers even tho its offline cuz of crashes 60% of the time

cold sonnet
#

and you are using a while true in a task

#

kills the entire point

slate swan
cold sonnet
#

no

#

docs didn't

slate swan
#

ok maybe it was stackoverflow but its almost as trusted as docs right haha

cold sonnet
#

no

slate swan
#

Stackoverflow is full of outdated and bad code

cold sonnet
#
                file = open("30 years old discord users"+str(ctx.guild.id), "w")
                file.write("enabled")
                file.close()
                file = open("channel"+str(ctx.guild.id), "w")
                file.write(str(ctx.channel.id))
                file.close()
#

and what that

slate swan
#

dude what

cold sonnet
#

man I'm not trying to be like that

#

this is just serious memory raping

slate swan
cold sonnet
#

had to

#

should I write its real name there shipit

tawdry perch
#

I read the stuff and now I regret it, too many things that I did not want to see

slate swan
#

file.write > cursor.execute

#

Wut no

#

TXT files aren't even meant to be used as database

#

well no shit

#

but it works so I use it

cold sonnet
#

okay but that was not my point 😦

slate swan
#

Sure , but this opinion is invalid

slate swan
cold sonnet
slate swan
#

hm

cold sonnet
#

I also prefer databases

slate swan
#

meh, I never even learned to use dbs in python

cold sonnet
#

tho I'm too lazy to make one most of the time

#

and my raspberry wouldn't do nothing with a database

#

it just crashed after downloading 55MB in 1 hour

slate swan
#

bro

#

ur using a rasperry pi

cold sonnet
#

yes

slate swan
#

...

cold sonnet
#

no you're not gonna bully the raspberry

tawdry perch
#

I have used dbs, they are quite nice

slate swan
#

scam romanian 20€/year vds 4gb ram > 20$ rasperry pi 500mb ram

lunar quail
#

Is it normal that attributes and methods of discord.Emoji don't work on emojis that are on a guild that the bot isn't on?
(I am trying to get the animated attribute of a emoji that is on a guild that bot isn't on)

tawdry perch
cold sonnet
slate swan
rugged marsh
#

use aioaqlite, quite easy

slate swan
slate swan
rugged marsh
cold sonnet
#

incase they want an ||autoporn|| system for their discord server

slate swan
#

not saying they wouldn't but I really dont care, its just a token (i have my reddit account password there too)

slate swan
rugged marsh
#

always better to setup yourself a physical server

slate swan
#

!d discord.Emoji.animated

unkempt canyonBOT
slate swan
rugged marsh
#

to host a discord bot?

slate swan
#

nah I'm gonna move my website and gameservers there too

#

when I have time

#

Don't you code the bot and stuff on the same device?

#

huh

#

I use a laptop for coding, way more comfortable to sit in bed while writing code than sitting on a damn chair

#

and the pc is unusable rn cuz it aint got a desktop env, only cli

dapper cobalt
slate swan
#

bro ur bed like one of those american prison beds or how can you think chair is more comfortable than a bed

dapper cobalt
#

It's more relaxing for my neck and back tbf. Btw, that's so off-topic innit?

slate swan
#

btw can I put activity= in commands.Bot()

final iron
#

!d discord.ext.commands.Bot

unkempt canyonBOT
#

class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.

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

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

**options

dire folio
#

How do you optional arguments?

#

For something like a ban command

slate swan
#

Set the default value to none or use typing.Optional

#

whats the exception for

discord.ext.commands.errors.CommandNotFound: Command "commandhere" is not found

full valley
#

is there a way to log the timeout feature yet

cedar stream
cold sonnet