#discord-bots

1 messages · Page 1088 of 1

slate swan
#

ahhh thanks, whats the character?

pliant gulch
#



#
Hello
#

If your gonna be sending the codeblock through the bot though, using \u001b would work

#

If your sending the codeblock through yourself, you'd have to use the actual character

slate swan
#

ok thank you

boreal ravine
#

bot raids?

slate swan
#

i think he means people botting his server

slate swan
#

im dumb eys lol

#

just realised

#

```ansi
text
```

pliant gulch
#

Really glad discord added ANSI support

#

Great addition

slate swan
#

guess im too slow 😔

pliant gulch
#

You can copy paste & use it

crisp drift
#

stop flexin

pliant gulch
#

If you want to, it's just much easier

slate swan
#

nice idea andy 😳

elfin moon
#

how do i send a DM to a user in an async function that is not a command?

pliant gulch
slate swan
#

use get_user to get the user, and use .send() method on it

slate swan
pliant gulch
#

no

elfin moon
#

it doesn't work

#

it only works inside a command

slate swan
elfin moon
pliant gulch
# pliant gulch no

Looking at your contribution, the only did you added was the discord widget to the README

slate swan
#

use fetch then...

elfin moon
slate swan
#

no i actually corrected the installation url

#

i did allot

slate swan
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/api.html#discord.Client.get_user "discord.Client.get_user") instead.

Changed in version 2.0: `user_id` parameter is now positional-only.
elfin moon
#

bruh the error is created in the line that sendds the message

pliant gulch
#

Okimii did some useless PR while sarth actually did something

elfin moon
#

so that doesn't help

slate swan
#

and member cache enabled,
do they even allow disabling it?

slate swan
elfin moon
# wicked atlas What error?

so when i try to send a DM to a user outside of a command function, i get this error Timeout context manager should be used inside a task but when i send it in a command it works

slate swan
elfin moon
#
async def onVote(userid):
    def isUserAvailable():
        return int(userid) not in farmusers

    condition = asyncio.Condition()
    await condition.wait_for(isUserAvailable)

    user = bot.get_user(int(userid))

    if user is not None:
        await user.send('Thanks for voting!')
slate swan
#

how do i set the discord embed colour to a random one each time?

#

forget everything, just use ```py
await bot.http.send_message(user_id, "some cool stuff")

slate swan
#

!d discord.Colour.random

unkempt canyonBOT
#

classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") with a random hue.

Note

The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.

New in version 1.6.
slate swan
#

remember color is an alias

slate swan
elfin moon
#

@slate swan that line doesn't work File "", line 13, in onVote TypeError: HTTPClient.send_message() takes 2 positional arguments but 3 were given

elfin moon
#

yeah

#

this is my modified code

async def onVote(userid):
    def isUserAvailable():
        return int(userid) not in farmusers

    condition = asyncio.Condition()
    await condition.wait_for(isUserAvailable)

    await bot.http.send_message(int(userid), "Thanks for voting!!")
slate swan
elfin moon
#

anything wrong with this python await bot.http.send_message(int(userid), "Thanks for voting!!")

#

the last parameter is unexpected

slate swan
#

thi what's your bot variable? is it already running?

wicked atlas
#

yeah, you should be sending messages to users with the User or Member objects. You shouldn't need to go to the http clients methods

wicked atlas
elfin moon
elfin moon
wicked atlas
slate swan
#

that aint working for them for some reason

wicked atlas
#

Well that's why I'm asking to see the error

elfin moon
#

File "", line 13, in onVote TypeError: HTTPClient.send_message() got an unexpected keyword argument 'content'

wicked atlas
#

I meant the error you were getting before, with your original code

elfin moon
#

oh ok

slate swan
#

what dpy version are you on? they made changes in 1.7.3 and 2.0's httpclient

elfin moon
#

2.0

#

File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/helpers.py", line 635, in __enter__ raise RuntimeError( RuntimeError: Timeout context manager should be used inside a task

wicked atlas
#

And the rest of the traceback?

elfin moon
#

uhh

#

i gotta replace all of my usernames lol

#

im on it

slate swan
#

wait did you just start the task before bot.run ?

elfin moon
#
Traceback (most recent call last): File "/Users/yourmom/Documents/discordbot/bot.py", line 276, in dblvote asyncio.run(onVote(842981557283323914)) File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/asyncio/base_events.py", line 641, in run_until_complete return future.result() File "", line 28, in onVote File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/abc.py", line 1493, in send channel = await self._get_channel() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 454, in _get_channel ch = await self.create_dm() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 496, in create_dm data: DMChannelPayload = await state.http.start_private_message(self.id) File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/http.py", line 441, in request async with self.__session.request(method, url, **kwargs) as response: File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/client.py", line 1117, in __aenter__ self._resp = await self._coro File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/client.py", line 448, in _request with timer: File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/aiohttp/helpers.py", line 635, in __enter__ raise RuntimeError( RuntimeError: Timeout context manager should be used inside a task
elfin moon
elfin moon
#

?

slate swan
#

how is this function invoked?

elfin moon
#

with asyncio.run(onVote(842981557283323914))

#

i was testing

wicked atlas
#

Are you calling it before calling bot.run?

slate swan
#

thats the issue, you bot is not even running and youre trying to use get_user and fetch_user

elfin moon
digital mason
#

I never expected bot verification to be that tough

slate swan
#
channel = await self._get_channel() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 454, in _get_channel ch = await self.create_dm() File "/Users/yourmom/.conda/envs/discordbot/lib/python3.10/site-packages/discord/user.py", line 496, in create_dm data: DMChannelPayload = await state.http.start_private_message(self.id)
``` targets to creating a dm with an invalid user
wicked atlas
#

That's not what the error means

elfin moon
slate swan
#

how do i edit an embed

elfin moon
wicked atlas
#

@elfin moon Try running the task using the bot's loop```py
bot.loop.run_until_complete(onVote(842981557283323914))

slate swan
#

How to get the most recent message of a channel in discord.py?

lyric apex
slate swan
#

channel.last_message :)

#

in an actual command instance I meant

sick birch
lyric apex
#

How to install jikashu?i installed it yet

slate swan
#

you need to await the client.load_extension

lyric apex
#

await client.load?

slate swan
#

use the setup_hook to load extensions!

lyric apex
#

Ahh got that

slate swan
#

!d discord.ext.commands.Bot.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
loud junco
#
from z.keep_alive import *
keep_alive()
#

i tried putting print('im aliveeeeeeeee') after keep_alive() but its not printed

#

its rate limited

#

just wait

#

to prevent api abuse i think

#

but its normal to get rate limited

#

i said its normal right? 🤣

#

:/ am i being rude

#

=.= visible confusion

#

whatever
sry ig

round knoll
#

not quite sure how you're trying to help

#

obviously im not a pro, thats why im asking here

slate swan
#

idk why this doesn't work

#
member = message.author
role = discord.utils.get(message.guild.roles, name = "test")
member.add_role(role)
boreal ravine
#

Await it

stone beacon
#

If you're getting rate limited on a daily basis then you're making too much requests simply

loud junco
#

because they dont use reload

#

so they keep on restarting i

heavy folio
#

simple: don't use replit
or dont spam stuff

round knoll
#

i see the params for discord.Guild are *, data and state. i cant find what they represent in the documentation. im not sure how to simply get a member list from it either? anyone can give some pointers?

slate swan
#

all you can do is wait, and man update the python version in the container, you're literally using 3.6

round knoll
#

im guessing i need to use a for loop to get individual items in discord.Guild.members? if i try to print(members_list) which stores the discord.guild.members, i get some memory adress. ive been in the documentations all day, i think im starting to see double lol

slate swan
#

it should be an instance of discord.Guild, not the class itself

round knoll
#

like this?

members_list =  discord.Guild()
print(members_list.members)
sick birch
#

Hence why it's not documented

#

Usually a guild instance will be provided for you can call .members on it

round knoll
#

yeha it could be that im totally not using the proper way to do what i want to do

sick birch
#
@bot.command()
async def print_members(ctx: commands.Context):
  print(ctx.guild.members)
#

Is one example

round knoll
#

im trying to check if the members in the discord have the ActivityType "streaming" and if they do, assign them the role LIVE

#

but i cant find much about it, and i guess im getting tired too loll

sick birch
#

You'll wanna use the on_member_update I believe the name is

slate swan
#

the most common ways of getting a guild object would be py context.guild if you have a Context

message.guild``` if you have a Message object ```py
bot.get_guild(server id)
``` if you have the server Id
sick birch
#

For your use case you don't need the guild at all

#

!d discord.on_member_update see this event

unkempt canyonBOT
#

discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.

This is called when one or more of the following things change...
sick birch
#

You can check if the after has a new activity with "streaming"

round knoll
#

nice, thanks a lot Robin!

sick birch
#

My pleasure, feel free to ping me or ask here again for further assistance

paper sluice
#

whats the equivalent of discord.TextChannel in lightbulb

slate swan
#

consider lightbulb as nothing more than the discord.ext.commands, its just a command handler
all the api related classes are provided by hikari

paper sluice
#

ah ok, thanks

#

and how do u get the channel from context of the command

slate swan
#

ctx.channel_id for the id
ctx.get_channel() for the channel

paper sluice
#

tyvm :)

round knoll
#

ok i think Robin was unto something. the streaming ID is different for every server or it's the same?

#

wait it's role id, sry

#

i found snippets of code written for discord.js .. not quite sure how to translate to python

sick birch
#

The hardest part is probably figuring out if a user has started streaming on_member_update, giving the role is easy peasy

round knoll
#

this is the part i think, but it's js

const updatedMember = await newMember.member.fetch();
await addRemoveStreamRole(updatedMember, !!updatedMember.presence.activities.find(a => a.type == "STREAMING"));
#

theres lots of commented stuff, im trying to retro engineer the thing with my very limited knowledge lol

#

found the intents thing and updated my bot instance with intents=intents

#

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

maiden fable
round knoll
slate swan
#

So I have a command with await winner.create_dm()
But if it fails to create the dm
My whole bot goes unresponsive

round knoll
#

can you wrap it in a try except block

fresh ferry
#

Im having trouble with my bot assigning a new role once i have it removing all roles from user → using it for a quarantine type bot

    for role in member.roles:
        if role.id in EXCLUDED_ROLES:
            return

    if config.QUARANTINE_ROLE not in member.roles:
        for word in res:
            if word[0].upper() in str(member.activities).upper():
                for role in member.roles:
                    if role.name != "@everyone":
                        await member.remove_roles(role),
                        await member.add_roles(role.id(QUARANTINE_ROLE))
                embed = discord.Embed(color=0xFF0000)
                embed.description = f"{member.mention} got quarantined because of word `{word[0]}` in his status!"
                await bot.get_channel(config.ANNOUNCEMENT).send(embed=embed)
                return
#

im stumped at what to do, this is making me very stressed trying to find a solution haha

regal pulsar
round knoll
regal pulsar
#

huh

slate swan
regal pulsar
#

oh

#

mb ;-;

slate swan
slate swan
slate swan
#

with a try except which catches discord.Forbidden probably

#

indeed!

#

i wish there was a way to check if a user has its dms open without actually dming them

slate swan
#

cz an endpoint for checking dm statuses seems weird

#

eh why an endpoint, it could just be a part of user's payload like .bot is, but again privacy issues

#

hm yeah, was thinking about the same but it won't really be a good idea even if it wasnt about privacy issues

#

looli who knows if sm1 had blocked only your bot specifically and the dms are open for others

#

totally not me and mee6

#

just close your dms from the privacy settings 😔

spring flax
#

can i have text centre aligned in an embed description?

slate swan
spring flax
#

what do you manually space it up?

#

with invisible chars?

slate swan
#

spaces should work too

spring flax
#

did i do it wrong?

slate swan
#

\u200b moment

spring flax
boreal ravine
paper sluice
#

how do i type hint an option, while invoking a command i type #discord-bots i want it to get the channel object and not a str

round knoll
slate swan
# spring flax

that will just get you a single space, its technically not possible to do what you're trying to, i mean try doing it in ur client ....

spring flax
#

you mean IDE?

slate swan
slate swan
#

cause GuildCategoryChannel are considered as TextableGuildChannel too

slate swan
paper sluice
spring flax
#

not sure what you mean

slate swan
#

like this

vague fiber
#

Hello everyone. I am having an issues with client.fetch_guild() that I'm hoping someone can help.
I have a cog with the following code in a command:

guild = await self.client.fetch_guild(guild_id)
print(len(guild.members))
async for member in guild.fetch_members():
            print(member.name)```
the first print, prints 0 and the iterator prints nothing. Does anyone have any ideas why I can not seem to retrieve the members?

I do have my presences set 
```python
intents = discord.Intents.default()
intents.members=True
intents.reactions=True
intents.guilds=True
intents.presences=True
client = commands.Bot(command_prefix= PREFIX, intents=intents)```
paper sluice
#

ya right, just notices the type param

round knoll
#

im trying to translate discord.js to discord.py

client.on('presenceUpdate', async (oldMember, newMember) => {
    // const guild = newMember.guild;
    // const streamingRole = guild.roles.fetch("972677238766063717");

    const updatedMember = await newMember.member.fetch();
    if(newMember.activities.find(a => a.type == "STREAMING")) {
        if(!updatedMember.roles.cache.has("972677238766063717")) {
            console.log("Adding streaming role to " + updatedMember.user.username)
            updatedMember.roles.add("972677238766063717");
        }
    }
    else {
        if(updatedMember.roles.cache.has("972677238766063717")) {
            console.log("Removing streaming role to " + updatedMember.user.username)
            updatedMember.roles.remove("972677238766063717");
        }
    }
    
    } );
slate swan
spring flax
#

if a message has 5 reactions, sum(single_reaction.count -1 for single_reaction in all_reactions) would be equal to len(reaction.message.reactions) -5 right?

round knoll
#
@loop(seconds=90)
async def set_live_role(oldMember, newMember):
    discord. # not sure how to implement the on_presence_update(before, after)
    updatedMember = await newMember.member.fetch()
    if newMember.activities.find("STREAMING"):
        if not updatedMember.roles.cache.has(LIVE_ROLE_ID):
            updatedMember.roles.add(LIVE_ROLE_ID)
        else:
            if updatedMember.roles.cache.has(LIVE_ROLE_ID):
                updatedMember.roles.remove(LIVE_ROLE_ID)
slate swan
#

dont tell me you just used some js to py converter for this

round knoll
slate swan
#

why does that look like djs

#

Ye

vague fiber
#

I haven't used listeners before but could you do something along the lines of listening for a members activity change and pass in the before activity and after activity?

round knoll
maiden fable
round knoll
#

its checking for activityType "streaming" i think

maiden fable
#

Yes

vague fiber
# round knoll i think thats what im trying to do

Yeah I don't know how that works in discord py. If someone knows they can elaborate. Otherwise you could brute force it and keep a dict or lists of tuples or something of all the people in the discord based on their id. Check everyones activity every 90 seconds and if they are streaming add the role and add it to the dict. If they already have the role, ignore it. If they have the role and are not streaming, remove the role and dict entry

boreal ravine
#

Firstly, do you know the basics of python?

round knoll
#

the only example i have working is with djs, so it complicates stuff.. i have no clue how to translate to python

boreal ravine
round knoll
round knoll
vague fiber
boreal ravine
round knoll
#

im already connected to discord api and twitch api, using it to post to discord and stuff. this is my last "feature" that i want

round knoll
#

yeah, im learning python. i dont have time to learn 2 language at once. one baby step after the other lol XD

vague fiber
slate swan
#

is there another way im meant to do this? im trying to see if a user left because they were kicked

spare urchin
#

um.. anoyne here ?

vague fiber
vague fiber
spare urchin
#

its sayig discord denied access ?

slate swan
#

your bots ratelimited

spare urchin
#

is it coz im using nextcord ?

slate swan
#

¯_(ツ)_/¯

vague fiber
# slate swan whats your error

The error is that the guild returned has no members in it's members attribute and guild.fetch_members() also returns no members

spare urchin
slate swan
vague fiber
slate swan
#

thats an automatic thing, it takes 1h to 3 days @spare urchin

spare urchin
slate swan
#

why dont you just use intents=discord.Intents.All()

spare urchin
slate swan
#

yes

spare urchin
#

well i dont understand a shit from its docs...

vague fiber
# slate swan try other guilds, maybe its a server error

I have. If I pass any of the guilds in using context. ctx.guild.members has all the members, but if I pass in buy guild id and do the fetch_guild the guild that is returned has the right name and id and stuff, but no members

spare urchin
#

;-;

#

i used their docs but it always shows client not defined

slate swan
#

theyre two different things

#

x = await self.bot.fetch_guild(id) makes an api call

#

x = self.bot.get_guild(id) doesnt make an api call, and is not awaited

vague fiber
#

Let me try the get_guild and see what happens

slate swan
#

try with guild = self.client.get_guild(guild_id)

vague fiber
#

Maybe since it is an api call, it isn't passing the proper intent along with it for some reason

slate swan
#

¯_(ツ)_/¯

#

and faster
thats kinda invalid, python is slower at most of the points

#

python can be the fastest lang, imo

round knoll
#

slower to run maybe, but faster to code and/or learn i agree

slate swan
#

indeed

slate swan
slate swan
round knoll
#

alright im not gonna solve my problem tonight. time to get some sleep. good night all.

slate swan
#

but thats straying from the topic, being discord.py

#

yes, you would be using the master branch of discord.py for that

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

and use the discord.ui.View class, install the library and ping me, ill help you out

slate swan
round knoll
# slate swan whats the issue

found some code from djs.. trying to translate it to dpy. simply put, i want to check for members in the discord when they get the streaming activity, and give them LIVE role. drop live role when not "streaming"

heavy folio
#

!d discord.on_presence_update

unkempt canyonBOT
#

discord.on_presence_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their presence.

This is called when one or more of the following things change:

• status

• activity

This requires [`Intents.presences`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.presences "discord.Intents.presences") and [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled...
slate swan
#

hi does it matter like

@commands.has_any()
@commands.command(name="@E")

can i put the commands.has_any()
up or down of @commands.command() with my choice if no where should i put it

heavy folio
# unkempt canyon

@round knoll so check if before.activity != after.activity and something

round knoll
heavy folio
#

what do you currently have

heavy folio
#

dont ping for help

heavy folio
#

and it doesnt matter position since its a decorator

slate swan
slate swan
round knoll
# heavy folio what do you currently have

i tried to just translate the djs file i found to dpy lol

# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 972677238766063717
@loop(seconds=90)
async def set_live_role(oldMember, newMember):
    discord.on_presence_update(oldMember, newMember)
    updatedMember = await newMember.member.fetch()
    if newMember.activities.find("STREAMING"):
        if not updatedMember.roles.cache.has(LIVE_ROLE_ID):
            updatedMember.roles.add(LIVE_ROLE_ID)
        else:
            if updatedMember.roles.cache.has(LIVE_ROLE_ID):
                updatedMember.roles.remove(LIVE_ROLE_ID)
slate swan
#

decorator positions do matter, not in this case
but they execute from bottom to top, not simultaneously all at once

#

okay

round knoll
#

its clearly not the way to go. but ive been coding and using documentations all day and my brain is fried lol

slate swan
# round knoll found some code from djs.. trying to translate it to dpy. simply put, i want to ...
act = f'{member.activity.type}'.replace("ActivityType.playing",
                                                            f"Playing {activity_name} {rich_presence}").replace(
                        "ActivityType.listening", f"Listening to {activity_name} {rich_presence}").replace(
                        "ActivityType.watching", f"Watching {activity_name} {rich_presence}").replace(
                        "ActivityType.streaming", f"Streaming {activity_name} {rich_presence}").replace(
                        "ActivityType.competing", f"Competing in {activity_name} {rich_presence}").replace(
                        "ActivityType.custom", f"{activity_name}")
@commands.Cog.listener()
async def on_member_update(self, member) -> None:
    guild  = self.bot.get_guild(your_server_id)
    member = guild.get_member(member.id)
    if discord.utils.find(lambda act: isinstance(act, discord.Streaming), member.activities):
        if role in member.roles:
            return
        if role not in member.roles:
            return await member.add_roles(your_role_id)
    
    if not discord.utils.find(lambda act: isinstance(act, discord.Streaming), member.activities):
        if role in member.roles:
            return await member.remove_roles(role_id)
        if role not in member.roles:
            return```
#

just wrote that up, should be good

round knoll
#

i dont think it would be approriate to share the 150 lines of codes in here tho?

slate swan
#

@round knoll i updated the code, that should work

slate swan
# round knoll i tried to just translate the djs file i found to dpy lol ```py # checks if disc...

good code dude, well; sort of. i know youre new to python, but the usage of if not value instead of if value == (None or False): is astonishing, i love seeing it especially from beginners. its very tedious dealing with people who dont actually know the trivial attributes of Python, so i personally thank you for taking the time to learn. in return, enjoy the spoonfeeding i just pasted above

#

tip: else: if ...: should be elif ...

#

wtf 😂

vague fiber
#

actually now that I think of it there is no need to check anyway because I completely forgot you can see their activity so easily

slate swan
#

🚶‍♂️ you guys are overdoing it

stiff gorge
#
line 209, in wrapped
    raise CommandInvokeError((exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: Replacement index 5 out of range for positional args tuple
    @commands.command(aliases=['server'])
    async def servers(self,ctx):
      if ctx.author.id in OWNERS:
        servers = self.bot.guilds
        servers.sort(key=lambda x: x.member_count, reverse=True)
        await ctx.send('***Top servers with Bot:***')
        for x in servers[:50]:
          await ctx.send('**{}**, **{}** Members, {} region, Owned by <@{}>, Created at {}\n{}'.format(x.name, x.member_count, x.owner_id,x.created_at,x.icon.url))
          y = 0
          for x in self.bot.guilds:
            y += x.member_count
            await ctx.send('**Total Bot users:** ***{}***!\n**Number of servers:** ***{}***!'.format(y, len(self.bot.guilds)))

can someone help

hollow agate
#

Hello, I currently have this: https://paste.pythondiscord.com/hezuvetutu

Where it has if question1.content == '': and else.
The else check only works once, how could I make it persist until question1.content == '':?

slate swan
#

ive never actually read the documentation for python, everything i know i know because i literally trialed every error before getting to my result, hence why my error handling is so profound (as seen in the code block i sent earlier)

round knoll
#

question Terror, does that function needs to be wrapped into a loop of 90 seconds? im not sure how it works

slate swan
#

!d any

unkempt canyonBOT
#
any

any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:

```py
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
slate swan
#

this is quite helpful.

#

thats when the functions called

round knoll
slate swan
stiff gorge
slate swan
#

x = []
if len(x) <= 50:
x.append(your info)

slate swan
slate swan
vague fiber
slate swan
#

also the python speed thingy looli c++ => ```cpp
#include <iostream>
using namespace std;

int main()
{
for (int i = 1; i <= 100; i++)
{
cout << i << "\n";
};
}```

for i in range(100):
    print(i)
``` a diff of 0.02 seconds in execution
slate swan
#

now lets see if anyone can solve my problem

#

im going to have a fucking aneurysm

ive been trying to figure this out all day, and nothing works.

@commands.Cog.listener
async def on_member_remove(self, member):
    queue   = [i async for i in guild.audit_logs(after=datetime.datetime.now() - datetime.timedelta(seconds=5), action=discord.AuditLogAction.kick)]
    if queue:
        member  = queue[0].user
        #do something to member
``` WHY does the `after` kwarg do nothing??!?!? i kicked a member 3 hours ago, and when a member leaves it still bans the person who kicked the member. Essentially i need to check if a member left because they were kicked
#

also, turns out the after kwarg is implied in the discord api documentation, its just been flagging errors since 2017 so discord decided to just not fix it

maiden fable
#

I mean that's expected from discord, sooo

slate swan
#

Hunter! we meet again. god, whats it been? 6 months?

#

3 months, i was close enough

maiden fable
#

Ah, hi there! Yup, long time indeed

slate swan
maiden fable
#

Nice, but actually that's a feature in a few bots in dpy server

slate swan
#

some really esoteric shit if u ask me

maiden fable
#

Cool!

slate swan
maiden fable
#

Good work nonetheless

slate swan
#

what've you been up to? any dpy breakthroughs?

maiden fable
#

Nah I have kinda took a hiatus from coding

slate swan
#

awh

maiden fable
#

Yea, personal issues haha

slate swan
#

are you running the bot somewhere else and not on your local device?

#

and its commands.Cog.listener()

maiden fable
#

Prolly that's the issue

slate swan
#

that should not run at all then pithink

heady sluice
#

doesn't after take a func

slate swan
#

and when a member leaves it still bans the person who kicked the member

#

they probably just missed it while sending it or maybe idk

#

maybe

heady sluice
slate swan
#

!d discord.Guild.audit_logs

unkempt canyonBOT
#

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

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

Examples

Getting the first 100 entries:

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

it's a datetime

#

😭

slate swan
#

and thats what they r using

#

@slate swan

If a datetime is provided, it is recommended to use a UTC aware datetime. If the datetime is naive, it is assumed to be local time.
this warning

heady sluice
#

after 5 seconds before

slate swan
heady sluice
#

it's youteesee

slate swan
slate swan
slate swan
heady sluice
round knoll
#

@slate swan hmm, i went for a test live and the bot did not assign the LIVE role. it did post to my discord tho! which was one of the feature. !ping and !hello works too

slate swan
slate swan
#

tf, english is weird

heady sluice
#

nah

slate swan
#

undoubtedly

#

🚶‍♂️

round knoll
#

lots of yellow highlights, not sure if normal.

pearl fjord
slate swan
#

yeah, i wrote it on the fly. lots of stuff there isnt defined

slate swan
pearl fjord
#

lol

slate swan
#

wait - i think its against the rules to say that 😓

pearl fjord
#

yep

slate swan
#

lemme revise

slate swan
#

ummmm it just says dont offer or ask for paid work, im just stating a price so idk

pearl fjord
round knoll
#

i dont think it's about the number of lines tho..

slate swan
#

im stuck in termux

#

or tell you which commands are favoured by usrrs

#

how do i import code??!?

round knoll
#

i could sell you 5000 lines of print("Hello world!") for 1k lol

slate swan
#

or what their past usernames are :P

pearl fjord
pearl fjord
slate swan
pearl fjord
#

not a bad idea actually

slate swan
slate swan
#

out of all your bots, whats the biggest one (linecount wise)

#

your bots. not Dyno

#

TypeError: str is not an int: "Dyno"

#

idk , all of the extensions are like 150-400 lines

stiff gorge
#
    ret = await coro(*args, **kwargs)
  File "/home/runner/mv/cogs/utility.py", line 81, in channelinfo
    embed.set_footer(text=("Created on {} ({} days ago)".format(channel.created_at.strftime("%d %b %Y %H:%M") (ctx.message.created_at - channel.created_at).days)))
TypeError: 'str' object is not callable
embed.set_footer(text=("Created on {} ({} days ago)".format(channel.created_at.strftime("%d %b %Y %H:%M") (ctx.message.created_at - channel.created_at).days)))

why is this wrong

slate swan
#

11737, my bots line counts (accounts for every bot file, excluding files that dont end in .py and files that stray from bot specific files (cogs, utils ect)

maiden fable
slate swan
#

well, 😔 its running and people use it LMAO

maiden fable
slate swan
#

a very fine anti nuke, actually. up to 1.2k lines now i think, week 2 😋

maiden fable
#

Won't be surprised if I take it down after a few weeks

#

Ngl I'm bored of discord bots. I wanna focus on other projects but can't gather enough motivation

slate swan
maiden fable
#

Nice, u making the bot answer to uwu
At least it's not like it's owner

slate swan
#

i'd never get bored with discord bots cause i never completed a bot looli

#

you cant ever complete a discord bot

maiden fable
#

Same, never completed a single project

slate swan
#

im done with 6-7 commands, and boom a rewrite in another library

#

and if you think youve completed a discord bot, you just need to process more ideas

#

youre never done, not with these projects

pearl fjord
#

why don't i ever get any message content from this bruuuu

#

ignore that its replit i needed to share it with someone

slate swan
#

yikes

maiden fable
#

message content intent

pearl fjord
slate swan
#

im up to 140 commands 😐

slate swan
pearl fjord
slate swan
#

and about 20 unique features

maiden fable
#

Sorry, my bad

slate swan
#

i wanna say.... 20 cogs?

pearl fjord
slate swan
#

unique. describe them pls

slate swan
pearl fjord
#

uh thats 1 command

slate swan
#

yes, a prime example

pearl fjord
#

he said describe them

slate swan
#

with no harcoding*

royal thunder
slate swan
#

ill just screenshot my bots changelogs which have not been updated in almost a month (i think, i have horrible time tracking skills)

royal thunder
#

Can anyone help me out

pearl fjord
royal thunder
#

I just shifted from js to python

maiden fable
pearl fjord
slate swan
#

@slate swan

round knoll
#

so role would be "LIVE" or the role id? im confused

pearl fjord
round knoll
#

also where is act used

slate swan
pearl fjord
slate swan
#

100, pending verification

pearl fjord
#

i replied to terror not you

pearl fjord
slate swan
#

mm then wait for his reply and see if it differs 🙂

slate swan
#

discord likes to take their fucking time with verification

#

ive sent 4 emails requests.

round knoll
#

alright i just need to fix those undefined variables

heavy folio
slate swan
slate swan
#

oh, my userinfo command?

#

i made that file back in August...

pearl fjord
#

"whats copied" you can tell 100% that it was copied from that because if it wasnt he would try to defend it instead of just dodging

slate swan
#

what aspect of it is copied

heavy folio
#

like the whole thing

slate swan
#

here? id love to see

maiden fable
slate swan
#

with the amount of data discord provides, a userinfo command would be really limited and almost same for all bots. so cant really frame something as a copy

maiden fable
#

U get pushed to a lower position in queue when u send a new email

maiden fable
#

Yea, I also learnt it the hard way

round knoll
slate swan
#

@maiden fable do u know how to use termux?

maiden fable
#

Never used it sorry

slate swan
#

...ok

stiff gorge
#
embed.add_field(name = "Created On", value =  "{}".format(channel.created_at.strftime("%d %b %Y %H:%M")))

how to make the created on message like this <t:1624385691:R>

slate swan
#

!d discord.utils.format_dt

unkempt canyonBOT
#

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

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

or simply , <t:<timestamp>:R>

round knoll
#

@slate swan that was yours right? the shorter code?

slate swan
pearl fjord
slate swan
#

you can if not LIVE_ROLE_ID in member._roles:

slate swan
slate swan
round knoll
slate swan
#

after._roles

#

after is your member object

stiff gorge
slate swan
stiff gorge
#

ohk

royal thunder
#

I have reset the token then also

round knoll
#

in the else: should i after.remove_role(LIVE_ROLE_ID) ?

slate swan
slate swan
round knoll
#
LIVE_ROLE_ID = 972677238766063717
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
async def on_member_presence_update(before, after):
    if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
        if not LIVE_ROLE_ID in after._roles:
            after.add_role(LIVE_ROLE_ID)
            
    else:
        after.remove_role(LIVE_ROLE_ID)
slate swan
#

same thing for add_roles too

round knoll
#

alright fixed

royal thunder
slate swan
#

@round knoll correct what invalid-user said^

round knoll
#

roger that, apparently, my id was wrong, even tho im sure i copy id from discord directly

#

retesting

heavy folio
#

sometimes that happens to me too

round knoll
#

alright do i need a loop wrapper on this, or it updates when the user activity changes?

#

is there a way to force a check?

slate swan
#

and yes there;s a forced way but dont use it 🙂

pearl fjord
#

Please, could someone have a look at #help-chestnut, I have a really weird problem

round knoll
#

ok, so to test this, i should manually give me the role, then stop the stream

#

it should remove it?

#

oh wait, do i wrap this on @bot.event

slate swan
#

yessir

jagged adder
#

how can i check if a certain file currently exists within my project? and then display a different msg if it does?

#

ive setup saves in my game, and they are stored as json files that are identified by the players id who used the save command

#

and i want to bring up a warning/confirmation msg if someone tries to save who alrdy has a save file

#

but to do that, i need to be able to check if that save file alrdy exists

round knoll
#

ive tried adding print statements to track role adding / removing

#

i get nothing

slate swan
#

does it get printed tho?

unkempt canyonBOT
#

os.listdir(path='.')```
Return a list containing the names of the entries in the directory given by *path*. The list is in arbitrary order, and does not include the special entries `'.'` and `'..'` even if they are present in the directory. If a file is removed from or added to the directory during the call of this function, whether a name for that file be included is unspecified.

*path* may be a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object). If *path* is of type `bytes` (directly or indirectly through the [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "os.PathLike") interface), the filenames returned will also be of type `bytes`; in all other circumstances, they will be of type `str`.

This function can also support [specifying a file descriptor](https://docs.python.org/3/library/os.html#path-fd); the file descriptor must refer to a directory.

Raises an [auditing event](https://docs.python.org/3/library/sys.html#auditing) `os.listdir` with argument `path`.
slate swan
#

you can get a list of filenames

spring flax
#

how do I use Messageable.fetch_message? can someone give an example?

maiden fable
#

ctx.channel.fetch_message()

spring flax
slate swan
#

textchannel is derived from messageable

spring flax
#

so these both below are the same?

#

!d discord.abc.Messageable.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.
spring flax
#

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

indeed.

maiden fable
#

TextChannel is a subclass of Messageable

left idol
#

working with pycord, is it possible to have one person send a command that gives them button options for approve and deny but only have members with a specific role click the button for them to work?

round knoll
#

added await

cursive barn
#

!d discord.Member.roles

unkempt canyonBOT
#

property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.

These roles are sorted by their position in the role hierarchy.
round knoll
#

still nothing

#

alright, i think it's enough for tonight, i dont think im gonna resolve this. altho i think were close

cursive barn
#

hey @round knoll you could also try a different approach like to add the role like ```py
if not member.get_role(LIVE_ROLE_ID):
await member.add_roles(member.guild.get_role(LIVE_ROLE_ID))

the function `get_role` is a method of the `discord.Member` class, allowing you to see if a member has a certain role. If they do, it will return that role instance. If they do not, it will return `None`.
#

discord.Object technically should be working, but at least in my experience I have noticed quite a few issues with it - so maybe just the long way for consistency

round knoll
#

alright, one last try then

#

modified, should i try now?

loud junco
#

lemme tp again #bot-commands

cursive barn
#

@round knoll im just reviewing your comparison logic

round knoll
#
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_presence_update(before, after):
    if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
        if not after.get_role(LIVE_ROLE_ID):
            await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
            print("Giving LIVE Role")
            
    else:
        await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
        print("Removing LIVE Role")
#

i cant take credit for any of this. this is way over my paygrade

#

sarth helped a lot, and invalid-user too

cursive barn
#

okay i have one review suggestion if it doesn't work as is and this is it ```py
if any(isinstance(activity, discord.Streaming) for activity in after.activities):
...

#

I think you should be a-ok to give it a go @round knoll

slate swan
#

do you have another on_presence_update?

cursive barn
#

this is a global event, so it would take precedence over a cog-specific one

#

@bot.event instead of commands.Cog.listener

slate swan
cursive barn
#

if failing to remove a role that isn't there in the first place raises an HTTP exception it is possible the exception is getting handled elsewhere and absorbed - causing the print statement to not execute

#

update @round knoll?

slate swan
#

@round knoll it that function by any chance placed below bot.run()?

round knoll
#

negative, nothing still

round knoll
slate swan
#

actually i got the issue, change on_presence_update to on_member_update

#

presence_update was added in 2.0

#

and they apparently have 1.7.3

slate swan
#

and add a print in the first line of the function to make sure it got executed

round knoll
#

who has 1.7.3?

slate swan
round knoll
#

oof

#

thats what i did

slate swan
#

just do the change i mentioned above, and it should be fine

round knoll
#
# checks if discord activity is streaming, if true, assign LIVE role, if Flase, remove LIVE role
LIVE_ROLE_ID = 983061320133922846
@bot.event
async def on_member_update(before, after):
    print("Zeddy bot is checking for roles")
    if any(a for a in after.activities if a.type == discord.ActivityType.streaming):
        if not after.get_role(LIVE_ROLE_ID):
            await after.add_roles(after.guild.get_role(LIVE_ROLE_ID))
            print("Giving LIVE Role")
            
    else:
        await after.remove_roles(after.guild.get_role(LIVE_ROLE_ID))
        print("Removing LIVE Role")
slate swan
#

yep that's it

#

make sure the user changes its presence

placid skiff
#

!e

my_list = [1, 2, 3]
print(any(a==3 for a in my_list))
unkempt canyonBOT
#

@placid skiff :white_check_mark: Your eval job has completed with return code 0.

True
placid skiff
#

yup it does

slate swan
#

!e print(any(a for a in (1,2,3))) # don't really need to

unkempt canyonBOT
#

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

True
placid skiff
#

yup but he checks the activity type

round knoll
slate swan
placid skiff
#

if he does the statement as i did he could rip off the if in his any function

round knoll
placid skiff
#

2.0 is available only with git

slate swan
#

yeah that after.get_role lol, change it back to if not LIVE_ROLE_ID in member._roles

round knoll
#

i got a removing LIVE role printed

#

lets check for Giving LIVE role print

#

Zeddy Bot#1618 connected to Discord.
Zeddy bot is checking for roles
Removing LIVE Role
Zeddy bot is checking for roles
Zeddy bot is checking for roles
Giving LIVE Role

lament depotBOT
round knoll
#

ITS WORKING

#

woooooooooooow

#

thanks for your time and your patience sarth

#

bed time, well deserved

slate swan
left idol
#

in pycord can i get the roles of whoever interacted with a button with interaction.user?

slate swan
#

yep :)

left idol
#

can i do user.roles?

slate swan
#

no, but you can interaction.guild.get_member(interaction.user.id). roles

#

basically, getting a Member from the User object

left idol
#

isn't getting it since its returning None

livid hinge
#

.topic

lament depotBOT
#
**Do you think there's a way in which Discord could handle bots better?**

Suggest more topics here!

livid hinge
#

yes

#

less pushy

#

dont force slash commands etc

#

dont send out annoying messages in DM

#

make verification 5 times easier

#

make heartbeat interval longer

#

allow self-bots

#

and on and on

placid skiff
#

they will never allow self bots xD

#

people will use them only for spamming

slate swan
#

Ppl are already using..

placid skiff
#

and they get banned fingerguns

maiden apex
#

hey, can someone help me, i don't know why but this little code break every other commands of the bot and idk why py @client.event async def on_message(ctx): if "jul" in ctx.content or "Jul" in ctx.content or "JuL" in ctx.content or "JUL" in ctx.content: await ctx.add_reaction('👽')

placid skiff
#

change client.event into client.listen()

maiden apex
#

tysm it's now working !

slate swan
#

Tarsier is smort

#

Tvriser*

#

Tvrasier*

#

Tvriser

placid skiff
#

Good morning to you too ashley

slate swan
#

heck

slate swan
#

again

#

Tvirser

#

uhhhh

tacit horizon
#

can discord bot know my discord time

slate swan
tacit horizon
#

the time show when msg send side of the name

placid skiff
slate swan
unkempt canyonBOT
#
Not gonna happen.

No documentation found for the requested symbol.

slate swan
#

uh

#

!d discord.Message.created_at

placid skiff
#

Look i'll make it more simple
you can read the vas an a

unkempt canyonBOT
slate swan
#

nvm, ill copy paste

placid skiff
#

Hahahahaha

slate swan
#

Tvrsier

tacit horizon
#

how does Dank Memer show time in embed footer 🤔

slate swan
#

!d datetime.datetime.timestamp

unkempt canyonBOT
#

datetime.timestamp()```
Return POSIX timestamp corresponding to the [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instance. The return value is a [`float`](https://docs.python.org/3/library/functions.html#float "float") similar to that returned by [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time").

Naive [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances are assumed to represent local time and this method relies on the platform C `mktime()` function to perform the conversion. Since [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") supports wider range of values than `mktime()` on many platforms, this method may raise [`OverflowError`](https://docs.python.org/3/library/exceptions.html#OverflowError "OverflowError") for times far in the past or far in the future.

For aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "datetime.datetime") instances, the return value is computed as:

```py
(dt - datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds()
```   New in version 3.3.

Changed in version 3.6: The [`timestamp()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp "datetime.datetime.timestamp") method uses the [`fold`](https://docs.python.org/3/library/datetime.html#datetime.datetime.fold "datetime.datetime.fold") attribute to disambiguate the times during a repeated interval.
jagged adder
#

i got 2 problems in the below; how do i get the msgs to send in my discord channel when the command is set outside the main bulk of the code, and secondly does the os.path.exists look right, because it doesnt seem to work

@bot.command(name='save')
@commands.check(save_check)
async def command_save(ctx: commands.Context):
    state = ctx.bot.game_states[str(ctx.channel.id)]
    state_json = jsonpickle.encode(state)
    if os.path.exists(rf'C:\Users\User\PycharmProjects\TRPG Bot\saves{str(ctx.author.id)}.json'):
        await state.game_channel.send('Save file already exists. Do you wish to overwrite existing save? __(Yes/No)__\n'
                                      '**Warning: This action cannot be undone.**'
                                      )
        state.valid_game_options = ['yes', 'no']
        confirm_msg = await bot.wait_for('message', check=lambda m: m.content.lower() in ['yes', 'no'] and m.channel == state and m.author == ctx.author)
        if confirm_msg.content.lower() == 'yes':
            # put warning here about overriding saves
            write_json(os.path.join('saves', f'{str(ctx.author.id)}.json'), state_json)
            await asyncio.sleep(2)
            await state.game_channel.send('Save Successful!')
        elif confirm_msg.content.lower() == 'no':
            await asyncio.sleep(2)
            await state.game_channel.send('Save Cancelled. Game resumed...')
    else:
        write_json(os.path.join('saves', f'{str(ctx.author.id)}.json'), state_json)
        await asyncio.sleep(2)
        await state.discord.game_channel.send('Save Successful!')
#

actually its only the msgs i got problems sending rn

placid skiff
#

wdym outside the main bulk of code

jagged adder
#

an instance of the game is run within a func, while the bot.command is run outside of that instance

#

another thing i want to do is covert the above into a function and nestle it inside the instance so only someone actually playing the game can use the command

#

thats what im trying to do rn

#

if i can itll solve the msg send anyways

placid skiff
#

Can i see the block of code where the game is running?

jagged adder
#

sec

#

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

jagged adder
#

thats the simplified version with most of the content cut out

slate swan
#

I have a problem with Youtube search python here is my code and the error

@bot.command()
@commands.guild_only()
async def play(ctx, *, mot_clé : str):
    print(f"Play")
    client = ctx.guild.voice_client
    link = f'{mot_clé}'


    if client and client.channel:
        video = VideosSearch
        musics[ctx.guild].append(video)
    else:
        ytdl_options = {
    'noplaylist': True,
    'default_search': 'auto'
}

    ytdl = youtube_dl.YoutubeDL(ytdl_options)

    video = ytdl.extract_info(link, download = False)

    if 'entries' in video:
        video_format = video['entries'][0]["formats"][0]
    elif 'formats' in video:
        video_format = video["formats"][0]

    url = video["webpage_url"]
    stream_url = video_format["url"]
    channel = ctx.author.voice.channel
    musics[ctx.guild] = []
    client = await channel.connect()
    await ctx.reply(f"Je suis là pour vous ambiancer")
    play_song(client, musics[ctx.guild], stream_url)```
#

Traceback (most recent call last):
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\THEO\cinébot\main.py", line 59, in on_command_error
raise error
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: 'str' object has no attribute 'stream_url'

placid skiff
jagged adder
#

wdym?

placid skiff
#

You can subclass the Bot class of discord.py or whatever package you are using

jagged adder
placid skiff
tacit horizon
#

can i get someones timezone with bot

jagged adder
placid skiff
#

It will come in handly, since you declare the bot in your game class with this one your game class will also be an instance of Bot

jagged adder
#

rn im focused more on fixing what i got than implementing new features

jagged adder
placid skiff
slate swan
# placid skiff The error is not there

Traceback (most recent call last):
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\THEO\cinébot\main.py", line 59, in on_command_error
raise error
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\THEO\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: 'str' object has no attribute 'stream_url'

placid skiff
#

yeah the error is saying that you are trying to use stream_url as an attribute of string object

#

so you will have something like var.stream_url somewhere

slate swan
#

So how to correct this ?

placid skiff
#

they are two fields with /n inside the value

placid skiff
slate swan
placid skiff
# slate swan no

File "c:\Users\THEO\cinébot\main.py", line 59, in on_command_error
raise error

slate swan
#

What should I change then ?

placid skiff
#

yeah

placid skiff
#

||Ash please take me out of here||

slate swan
#

so I remove raise error ?

#

I still need to fix a couple of things in the code

placid skiff
placid skiff
magic pond
#

its still not registered for me

#

12hrs done

slate swan
placid skiff
#

WHAIT WTF I'M PROVIDING HELP ON SOMETHING RELATED TO YTDL

#

ASH WHY U DIDN'T STOP ME

slate swan
placid skiff
stiff gorge
#

wht can i do if the hybrid commands doesn't get registered ?

slate swan
#

Excuse me Blvck

placid skiff
slate swan
#

How to make a button which can only be clicked by a user with a particular role?

slate swan
slate swan
bronze gyro
#

lets say you have a generator of integers, how do you make it a list and remove all the 7's from it in one line

Can someone help me with this?

slate swan
# slate swan Outside the class?
class UwUButtonViewClass(discord.ui.View):
  async def interaction_check(interaction: discord.Interaction) -> bool:
    return (role in interaction.author.roles)
bronze gyro
#

lets say you have a generator of integers, how do you make it a list and remove all the 7's from it in one line

Can someone help me with this?

bronze gyro
#

Ok

#

sorry

slate swan
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.

Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
stiff gorge
#

should i install any lib to use slash cmnd in dpy 2.0 ?

placid skiff
#

Nope

stiff gorge
#

uhh

#
import datetime as dt
import json
import random
from datetime import datetime
import discord
import requests
from discord import app_commands
from discord.ext import commands


class hyb(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.hybrid_command(name="pingo")
    async def ping_command(self, ctx: commands.Context) -> None:
      await ctx.send("Hello!")

async def setup(bot: commands.Bot) -> None:
    await bot.add_cog(hyb(bot),guilds = [discord.Object(id = 845317571301081158)])
    print('hyb')

is this correct ?

slate swan
#

sure

#
discord.Embed(title="Some title for the embed", description="description for the embed", colour/color=hexcode/rgb/discord.Colour/discord.Color, url="url to make the embed title a hyperlink") #NOTE: All the arguments in the __init__ constructor of Embed class are optional

embed.add_field(name="name for the field", value="some value", inline=False) #NOTE: Every argument except "inline" is required
slate swan
#

👀

slate swan
slate swan
#

nothing

placid skiff
#

Uhm

slate swan
#

..

placid skiff
#

interesting

slate swan
#

?

slate swan
placid skiff
slate swan
#

huh?

random vigil
#

Guys, I wanna make a bot for counting. At least it should delete all messages which contains any letters and symbols in it, only numbers are available!
Second, if someone know, how to make participants send numbers only in order, for example: 1 2 3 4, but if after that someone sends 55, the bot should sting him - because there should not be 55 but 5!

Please help me 🙂

placid skiff
#

create a list of command groups with the embed already in them and when someone click the button you show that embed, without removing the rest of the buttons

stable leaf
#

how can i make command that when triggered it will send a message/embed with reaction and when you click the reaction it will do something?

#

idk how to make the check

devout iris
#

How to check channel permissions?

#

I need to check if everyone role sees a channel. If message read == True for everyone role ....

placid skiff
unkempt canyonBOT
#

discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.

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

i know this one but i don't want a event, i want it to be in command

#

does it work still the same?

slate swan
#
@client.command()
async def edonate(ctx, event, prize, *, msg):
  embed1 = discord.Embed(title=f"{ctx.author.name} wants to make an event donation!", description=f" \n:dot_877959363388641300:**Event:** {event} \n:dot_877959363388641300:**Prize:** {prize} \n:dot_877959363388641300:**Message:** {msg}", color = discord.Colour.random())
  embed1.set_author(name=ctx.guild.name)
  await ctx.send(embed=embed1, view=Buttons1())
``` embed sent twice
placid skiff
#

The event is called whenever a reaction is addedd so it will work for the command too, otherwise you can use wait_for to check for a single event

#

!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.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.

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

This function returns the **first event that meets the requirements**...
stable leaf
#

idk how to use this one

#

so i guess i will use on_raw

placid skiff
#

there are examples on the documentation

#

open it

stable leaf
#

kk

slate swan
#

I suggested holding a 'Python Object Oriented Programming Seminar', but the acronym was unpopular.

placid skiff
unkempt canyonBOT
#
Out of the question.

No documentation found for the requested symbol.

slate swan
#

I had a problem so I thought I'd use Java. Now I have a ProblemFactory.

placid skiff
#

lmao

placid skiff
unkempt canyonBOT
#

permissions_for(obj, /)```
Handles permission resolution for the [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role").

This function takes into consideration the following cases...
placid skiff
#

Where are those money stored?

#

you need to edit that json of that member then

#

Well if you don't do it the money will remain as they are stored

#

whatever changes you do you will have to change it into the json too

#

you will have to write it D_D

#

things will not be done with magic D_D

#

there is no "builtin" relations between a member object and the data stored in your json

#

so every changes to the member object must be done in the json too

#

that will change the value for your code only

#

in that code you edit your json in your last two lines

slate swan
slate swan
#

can u show code

#

uh

#

what the-

#

why would you do that, just why

#

....Hunter?

#

nice

maiden fable
#

Nvm

#

!d discord.Member.guild_permissions *

unkempt canyonBOT
#

property guild_permissions```
Returns the member’s guild permissions.

This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").

This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.

Changed in version 2.0: Member timeouts are taken into consideration.
maiden fable
#

Nice

slate swan
#

the error pretty much says it all

#

how make dizcord bot

#

no.

#

ok

#

at least tell them what tutorial pBear

maiden fable
#

U r tryna add all the permissions in one single value

slate swan
#

Hunter's smort

#

how to get the highest role the bot can access and the role that are lower than the highest role

slate swan
#

Hunter, that doesn't help

#

ye

slate swan
#

i was making a lock command basically

#

the role that falls on the superior hierarchy, right?

maiden fable
slate swan
#

no

slate swan
unkempt canyonBOT
#

property top_role```
Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.
slate swan
#

i dont mean that

#

but that's not what Sparky wants

maiden fable
#

I forgot that existed

slate swan
#

the highest role that bot can edit

#

and the roles lower than that

slate swan
#

hm

maiden fable
#

Thats not how a lockdown command works tho @slate swan

slate swan
#

^

#

huh

maiden fable
#

Mb

slate swan
#

you gotta change the channel's permissions

#

channel.overwrites_for(ctx.guild.default_role)

maiden fable
#

U edit the permissions for everyone role

slate swan
#

that doesnt work ..

#

some ppl can still send msg!

#

ok so

#

@slate swan stop

#

what

#

dont delete messages!

#

okay!

maiden fable
slate swan
#

it does lock but ppl having different role can send msg

#

😐

maiden fable
#

Sad

slate swan
maiden fable
#

Uhhh

#

Can I see some code?

slate swan
# maiden fable Can I see some code?
channel = channel or ctx.channel
     overwrite = channel.overwrites_for(ctx.guild.default_role)
     if overwrite.send_messages == True:
       try:
          embed = disnake.Embed(description=f"Locked {channel}",color=green,timestamp=datetime.utcnow())
          await channel.set_permissions(ctx.guild.default_role, send_messages=False)
          await channel.send(embed=embed)

       except:
          embed = disnake.Embed(description=f"Cannot lock {ctx.channel}",color=red,timestamp=datetime.utcnow())
          await ctx.reply(embed=embed)
     else:
          embed = disnake.Embed(description=f"{channel} | Is Already locked",color=red,timestamp=datetime.utcnow())
          await ctx.reply(embed=embed)
maiden fable
#

Does it send the embed in the except block?

slate swan
vale wing
#

Why x == True when you can just x

#

Just code style hint

slate swan
vale wing
#

Ok

slate swan
#

i guess i added it when i was learning

vale wing
#

Ig the problem is the send_messages may also be None

slate swan
#

um let me check

vale wing
#

You should kinda revert your if construction

#

Check if overwrite.send_messages is False and execute the code you had in else statement

slate swan
#

i tried printing

vale wing
#

Means the permission is not set and basically it is true

slate swan
#

alr let me reverse

stable leaf
#

how can i deleted channel using his name

slate swan
#

@vale wing worked 💀

vale wing
vale wing
slate swan
#

i also got locked 💀

vale wing
#

Lmao

stable leaf
#

so yes

vale wing
#

You can just typehint channel argument with TextChannel, it will automatically find the channel with that name if it exists

slate swan
vale wing
#

Np

stable leaf
#

ok

vale wing
#
@bot.command()
async def delete(ctx, channel: discord.TextChannel):
    await channel.delete(reason=f"Deleted by {ctx.author}")```
#

Something like this

#

Don't forget to add checks so common users can't use this command

stable leaf
#

i don't want that like this sorry i'll explain

#

i have bot that creates a channel for party with that person he selected so the name is {ctx.author.name} {member.name} and i want command that when you type something like this -partyend {member: discord.Member} it will delete the channel

#

is that possible?

slate swan
#

cant understand

slate swan
#

ok i understand now

stable leaf
#

i have command -connect member that will create private channel for you and the member. the name of the channel is your name his name

boreal ravine
slate swan
stable leaf
slate swan
stable leaf
#

yes

#

and i know you can delete channel using his id or name but i forgot how to do it

boreal ravine
#

You mean.. discord.abc.GuildChannel.delete/discord.TextChannel.delete

stable leaf
#

just delete a text channel

#

but with specific name

boreal ravine
stable leaf
#

i'll try

buoyant nymph
slate swan
#
async def party(ctx,member : discord.Member):
    await ctx.guild.create_text_channel(name=member.name)
async def partyend(ctx,member : discord.Member):
    a = discord.utils.get(ctx.guild.channels,member.name)
    await a.delete()
buoyant nymph
#

I need that badge

#

Command

stable leaf
#

?

slate swan
#

..

stable leaf
#

i combined those two into one

#

thx @slate swan

#

thx @boreal ravine

slate swan
#

👍

stable leaf
#

how would i delete a voice channel?

voice = get(ctx.guild.voice_channels, name=f"{ctx.author.name} {membed.name}")
#

like that?

slate swan
#

voice.delete()

stable leaf
#

but is it ctx.guild.voice_channels?

slate swan
#

ctx.guild.voice_channels , yes

stable leaf
#

thx

random vigil
#

Guys, I wanna make a bot for counting. At least it should delete all messages which contains any letters and symbols in it, only numbers are available!
Second, if someone know, how to make participants send numbers only in order, for example: 1 2 3 4, but if after that someone sends 55, the bot should sting him - because there should not be 55 but 5!

Please help me 🙂

#

Just do to everyone permission view the channel, but disable connect permission to voice channel . Really no need bot for this

#

Why did you asking then

#

Oh ok

random vigil
#

Yeah ok sure

#

Voice of course

#

It is discord bots channel...

random vigil
#

Right bro

#

It is only for you

#

For all members it is locked

#

It is only for admins

#

Not any way, for all members it looks like you wants for admins and owner no

#

Because admins can do anything, and connect to anything

#

Try to view server as member

scarlet aurora
#

hello

random vigil
#

Nah it is not

#

Yes, you just did it

#

If someone have admin permission or permission to connect, they can join it

#

Not any way

#

I didn’t understand you.. You cannot lick channel from yourself

#

YOU JUST DID IT, VIEW your server as “member” role

#

And you will aee, this channel is locked

#

Check in YouTube.. it is working.

#

I know, but he not

random vigil
#

Please...

#

Yeah

scarlet aurora
#

does anyone know why my bot.user.id is giving none for the first 2 seconds on boot

random vigil
#

Guys, I wanna make a bot for counting. At least it should delete all messages which contains any letters and symbols in it, only numbers are available!
Second, if someone know, how to make participants send numbers only in order, for example: 1 2 3 4, but if after that someone sends 55, the bot should sting him - because there should not be 55 but 5!

Anyone can help, I just wanna counting bot😦

scarlet aurora
#

bot command

scarlet aurora
#
@bot.command()
async def pay(ctx, amount, discord.Member = None)
    ....
random vigil
#

Yeah it is bot command. You should have prefix ~ first of all. If you have,

random vigil
#

Oh ok

scarlet aurora
#

just change bot.command() to client.command() @slate swan

#

i assumed u defined it as bot since bot > client

#

well lemme see ur code

#

so i can see how ur currency works

slate swan
#

!code

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.