#discord-bots

1 messages · Page 794 of 1

onyx viper
#

it's dead rn

slate swan
#

My code just stopped working?

fervent shoal
#

same

#

it worked yesterday perfectly fine

slate swan
#

This worked fine yesterday?

quaint epoch
#

is there a bot event to check if being ratelimited?

quaint forum
#

Im pretty new to python and Im just watching this video right now, https://www.youtube.com/watch?v=wjQ9Nin21d8&list=LL&index=53 and when he begins to code it sounds like you have to include that little line of code in order for the bot to even function

Understand how to code a discord bot without spending an hour watching a tutorial. Our goal is to cut all the fat from learning and allow you to move onto bigger and better things!

After this python tutorial you will be able to create a custom discord bot from scratch. In this video we will cover responding to message events and creating bot c...

▶ Play video
#

He says to use on_ready but what is @discord.Client().event?

bold surge
#

thats never used...

quaint epoch
#

what does bot.reload() do? does it need parentheses

quaint epoch
#

uhhhh wut

#

who uses the class to make the decorator?

#
import discord
client = discord.Client()```
boreal ravine
#

not a thing

quaint forum
boreal ravine
quaint epoch
#

strange

#

pycharm is acting dumb again

boreal ravine
quaint epoch
boreal ravine
#

brb

quaint epoch
#

see? the object has it but not the class

boreal ravine
#

disnake..

maiden fable
#

What happened

bold surge
slate swan
#

!d disnake.ext.commands.Bot.reload

unkempt canyonBOT
#

Whether to enable automatic extension reloading on file modification for debugging. Whenever you save an extension with reloading enabled the file will be automatically reloaded for you so you do not have to reload the extension manually. Defaults to False

New in version 2.1.

quaint epoch
slate swan
#

^

quaint epoch
#

alr

slate swan
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
pallid mango
#

oof

#

i forgot

trim dirge
#

Can anyone explain to me why these commands aren't working?

from discord.utils import get

TOKEN = ''

client = commands.Bot(command_prefix="?")

@client.command()
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)

    if voice is not None:
        return await voice.move_to(channel)

    await channel.connect()

    await ctx.send(f"Joined {channel}")

@client.command()
async def leave(ctx):
    channel = ctx.message.author.voice.channel
    voice = get(client.voice_clients, guild=ctx.guild)

    if voice and voice.is_connected():
        await voice.disconnect()
        print(f"The bot has left {channel}")
        await ctx.send(f"Left {channel}")
    else:
        print("Bot is not in a vc")
        await ctx.send("I am not in a vc")

client.run(TOKEN)```
spring verge
#

Btw if I make a project like discord bot then do you guys recommend buying another domain for it's website? Or use subdomain in the main website? By main website I mean like "supercell" created "clash of clans" so the game is a subdirectory of supercell.com

quick gust
#

That's honestly whatever you want to do

#

But buying another domain seems useless to me since you can advertise the main website and the bot website with a subdomain instead

final iron
#

!d disnake.Member.voice

unkempt canyonBOT
#

property voice: Optional[disnake.member.VoiceState]```
Returns the member’s current voice state.
final iron
#

Saying that they aren't working doesn't help anyone

trim dirge
slate swan
trim dirge
#

Should I send the full code?

rain olive
#

if u have on_message event thats what causes no command uwuwuwuw

sick birch
#

process_commands(message) will fix that up, that or you can use a listener instead

slate swan
#
Ignoring exception in command userinfo:
Traceback (most recent call last):
  File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\rebellion\Desktop\cult\cogs\utility.py", line 33, in userinfo
    await ctx.send(embed=e)
  File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\abc.py", line 1065, in send
    data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
  File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.2.value: This field is required

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

Traceback (most recent call last):
  File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\rebellion\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\rebellion\anaconda3\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: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.2.value: This field is required

#

code:

    @commands.command(aliases=['ui'])
    async def userinfo(self, ctx, member: discord.Member = None):
        member = ctx.author if member is None else member
        roles_string = ', '.join([r.mention for r in reversed(member.roles[1:])])
        permissions_string = ', '.join([str(p[0]).replace("_", " ").title() for p in member.guild_permissions if p[1]])

        e = discord.Embed(
            timestamp=datetime.utcnow(),
            color=0x99FFFF,
            description=member.mention
        )
        e.set_thumbnail(url=member.avatar_url)
        e.add_field(name=f'Joined', value=member.joined_at.__format__('%a, %b %d, %Y %I:%M %p '))
        e.add_field(name=f'Registered', value=member.created_at.__format__('%a, %b %d, %Y %I:%M %p '))
        e.add_field(name=f'Roles [{len(member.roles[1:])}]', value=roles_string, inline=False)
        e.add_field(name=f'Key Permissions', value=permissions_string, inline=False)
        e.set_footer(text=f'ID: {member.id}')
        e.set_author(icon_url=member.avatar_url, name=member)
        await ctx.send(embed=e)
#

for some reason it's giving me an error on sending even though it's supposed to work

#

anyone got an idea?

pliant gulch
#

You'd need a persistent data storage for that, It's very likely there will be some downtime within the time-frame

#

Your task would restart back to the start unless otherwise made to work persistently

sick birch
#

You could store it as a unix timestamp somewhere (preferably in a database) and if the bot restarts, you can figure out how much longer until you have to remind them

#

Probably a more efficient way to do it though

sick birch
#

haha, thanks just got it :D

slate swan
sick birch
#

Thanks! Had a really warm welcome 😄

slate swan
#

love to hear itpithink

candid hill
# quaint epoch strange

That's more of a problem due to the way Python is built. It's difficult to statically analyze classes due to the nature of Python.

light violet
#

how to ban someone with request to discord api?

sick birch
#

discord.Member objects have a .ban() coroutine

pliant gulch
#

Yep, tasks would be the right choice here

light violet
#

i dont want to ban with it it is slower ban idk why nukers bypasses it's ban spd i need more speed for my antinuke anti ban and ban then fast before they could ban someone else

#

i want to use aiohttpx btw dk how to

pliant gulch
#

You can

light violet
#
@commands.Cog.listener()
    async def on_member_ban(self, guild, user):
        start = datetime.now().timestamp()
        reason = "R Anti-Nuke | Banning Members"
        async with aiohttp.ClientSession(headers=self.headers) as session:
                    
                async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
                            took = round((datetime.datetime.now().timestamp() - start), 3)
                            log = await r.text()
                            if r.status in (200, 201, 204):
                                logging.info("Successfully banned %s" % (user))
                                c = self.bot.get_channel(892973735802449943)
                                await c.send(f"Banned %s, took: {took}" % (user))
                            else:
                                logging.error(f"Could not ban %s" % (user))```
light violet
slate swan
#

youre gonna get flagged as a nuker prob

#

bans are slow because there dynamic iirc andy knows

light violet
sick birch
#

:D Thanks!

light violet
#

no btw my frnd made darkz sec and it uses aiohttpx and it bans nuker faster

#

than mine @slate swan

sick birch
slate swan
#

thats the thing youre banning to fast

light violet
slate swan
light violet
#

how did my frnd bot do it then

sick birch
light violet
slate swan
unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
pliant gulch
slate swan
#

i think you replied to the wrong msg andy?

pliant gulch
#

I did

slate swan
#

lol

light violet
#

i just use normal antiban btwjust wanted to make it faster any how

 @commands.Cog.listener() 
    async def on_member_ban(self, guild, member):
     if self.db.find_one({ "guild_id": guild.id })['toggled'] == True:
        logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
        logs = logs[0]
        reason = "R- DYNAMIC PROTECTION | ANTI BAN"
        whitelisted = self.db.find_one({ "guild_id": guild.id })['whitelisted']
        if logs.user.id in whitelisted:
            return
        punishment = self.db.find_one({ "guild_id": guild.id })['punishment']
        if punishment == 'ban':
            try:
                await logs.user.ban(reason=f"{reason}")
                return
            except:
              pass
        if punishment == 'kick':
            try:
                await logs.user.kick(reason=f"{reason}")
                return
            except:
              pass``` i just used to use this btw this is not faster how to make it faster ? allacrity named nukers bypasses my bot and does 50 bans btw on my frnd's bot it performs only 8 bans and get banned
#

?

slate swan
#

you cant make it faster

light violet
#

how that only idk , i am a simple beginner

#

dont know advanced

slate swan
#

the api wrapper must handle the ratelimits so it handles it so you wont get ratelimited if you request it directly to the endpoint you will just get ratelimited if you ban many members

light violet
#

ok btw for that they have a backup i think so cuz if my bot stops them at 8 bans then it wont cause rate limit i think so instead of 50 bans

#

@slate swan

slate swan
#

why the ping

light violet
#

and my frnd gave me this

@commands.Cog.listener()
    async def on_member_ban(self, guild, user):
        start = datetime.now().timestamp()
        reason = "R Anti-Nuke | Banning Members"
        async with aiohttp.ClientSession(headers=self.headers) as session:
                    
                async with session.put("https://discord.com/api/v9/guilds/%s/bans/%s" % (guild.id, user), json={"reason": reason}) as r:
                            took = round((datetime.datetime.now().timestamp() - start), 3)
                            log = await r.text()
                            if r.status in (200, 201, 204):
                                logging.info("Successfully banned %s" % (user))
                                c = self.bot.get_channel(892973735802449943)
                                await c.send(f"Banned %s, took: {took}" % (user))
                            else:
                                logging.error(f"Could not ban %s" % (user))```

btw this used to work before not now 😦
#

sorry

slate swan
#

just use the coro tbh why make a request to the endpoint

light violet
slate swan
#

theirs a reason why the wrapper manages the request

light violet
slate swan
light violet
#

then i dont think any thing would happen

#

lol

light violet
slate swan
#

why wouldnt it

slate swan
light violet
#

ooo

torn sail
sick birch
#

The code also looks much cleaner & easier to understand

blazing coral
#
async def on_member_join(ctx, member: discord.Member):
    logchannel = client.get_channel(911702069839294516)
    embed = discord.Embed(title=member.name, description=member.mention, color=discord.Colour.red())
    embed.add_field(name="ID", value=member.id, inline=True)
    embed.add_field(name="member joined on ", value=member.joined_at, inline=True)
    await logchannel.send(embed=embed)``` this will not work doesn't send an error just doesn't work on insight on why would be appreciated.
sick birch
#

How does it "just not work"?

#

Is it picking up the event? (a print statement inside would help)

pliant gulch
#

Do you have it?

blazing coral
#

let me check

pliant gulch
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

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

from discord import Intents
from discord.ext import commands

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

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

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

pliant gulch
#

should look like this

blazing coral
#

have intents

slate swan
#

!d discord.on_member_join

unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

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

ah yeah that's probably why

strong vessel
#

what is the best discord python? discord.py nextcord or something else?

sick birch
#

good catch didn't see that

slate swan
blazing coral
sick birch
slate swan
#

prob hikari

slate swan
#

hikari or Disnake

#

yeah

sick birch
#

and don't feel pressured to use a fork, even as a verified bot you can get by with updating d.py yourself with the newest features

slate swan
#

some verified bots still use 1.7.3 or main branch

#

if you have message intents

#

yup

#

if you get it

#

or use the bot's mention as prefix lol

sick birch
#

I don't think we can help with that, since you can easily repurpose it to spam someone else's DMs

slate swan
#

doesnt the bot need to fine <@itsid>? in the content of the msg?

slate swan
# slate swan how?

commands.when_mentioned

And you get all message properties if you are.mentioned in the message

#

ah yeah good point

slate swan
pliant gulch
#

get_user is not a coroutine, you do not await it. and get_user won't work as tasks start before the cache is populated. You need to wait for the cache

#

!d discord.ext.commands.Bot.wait_until_ready

unkempt canyonBOT
#

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

Waits until the client’s internal cache is all ready.
pliant gulch
#

You also don't need to create the DM yourself, just use the send method

delicate geyser
#

!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.
pliant gulch
#

Note, get_user is not a coroutine like I said above

strong vessel
#

do discord bots get banned a lot?

sick birch
#

Only if you break the TOS

strong vessel
#

like do they give warning before banning it or do will they IP ban me from discord

pliant gulch
#

Does print(f"{bot_settings['name']} - {bot_settings['version']}: All logs posted to relevant guilds.") run? It could be that asyncio.wait hasn't finished unblocking

strong vessel
#

just trying to see how cruel their banning is

#

for bot developers

pliant gulch
#

Does it print the second time around?

polar ice
#

Yes prints the second time around too. This is whats confusing me

slate swan
pliant gulch
#
        if guild.id not in server_settings:
            continue  # no settings for this guild, skip to next one
```? Maybe this? Not sure
sick birch
polar ice
#

After some de-bugging im thinking its maybe something to do with the SQL as ive put prints inside the functions and they print too?

strong vessel
#

i'm not doing anything malicious just that, like people might report my bot just to troll me

sick birch
#

Don't have to worry about that

strong vessel
#

i'm not breaking TOS but i don't want to suffer some extreme consequence for as punishment for making a bot

sick birch
#

False bans are rare and I'm sure discord will help you get it sorted

strong vessel
#

thanks

slate swan
#

Start the loop?

#

Or maybe the get_user retuurns none

#

Or the user isnt in any server with the bot

sick birch
#

If that were the case we'd have a NoneType has no send() method exception or something along those lines

#

Is that the case?

slate swan
sick birch
#

Hoping we don't have bad error handlers yes

slate swan
#

Did you start the loop?

slate swan
#

Hm

sick birch
#

Where are you starting it from? __init__?

pliant gulch
#

You are passing self to the method, so to me it seems like it's bound to a class. But when you call .start it isn't from a class?

#

If it's bound to a class you need to do instance.reminders_message.start()

sick birch
#

Doing it from __init__ is probably the easiest but it would work from anywhere within that class really

pliant gulch
#

instance is a generic variable name, the instance you use is the instance of your class, or in this case Cog

mild token
#

which lib for bots we are following here

pliant gulch
#

__init__

#

Like robin said

sick birch
#

__init__ will provide you with self

#

Actually any non-static or classmethods should do that which is why I said you can start the loop from anywhere in the class

solid bay
#

Are there any good discord API wrappers for python that are being actively maintained?

slate swan
solid bay
#

Are all of the libs forks of dpy?

slate swan
#

Two of the popular forks are, disnake and nextcord

#

Others are made completely from scratch

#

Like hikari

sick birch
boreal ravine
#

py-cord is a fork of d.py

slate swan
boreal ravine
#

there is pycord and py-cord

#

which one?

slate swan
slate swan
rancid tendon
#

What would be faster and more efficient:
Saving server settings into .json or in a sqlite3 db?
Or even mongodb?
I currently have .json files for small stuff and a sqlite3 db for some settings (blacklist/whitelist f.e.).

And how could I be sure that my db is secure enough? I know of SQL injection and how to prevent it on inserting data into the db, but I also want to make a web dashboard now and maybe open my bot up for public usage

boreal ravine
rancid tendon
sick birch
#

.json is usually more suited for static data like configs and whatnot

rancid tendon
#

Ok, thanks a lot ^^

#

It should be secure enough for my usage, right?

echo wasp
#

So I role on join one role do I need to make multiple role on join events or can I combine them into one? With comas? Something like this many in one event? List: @❗️Server Notify @✨ Highlights Ping @📩 Vote ping @🤝 Partners Ping @🙋‍♂️he/him @🙋‍♀️she/her @👫they/them @🙋‍♂️👫he/they @🙋‍♀️👫she/they @🕹Gamer @😂Meme Master @🎻Musician and @🎨Artist

vocal snow
sick birch
#

Are you asking for help with something or?

#

I think if you're asking can you assign multiple roles at once, member.add_roles() can be used, and you can pass in a list of snowflake objects

sick birch
rancid tendon
#

@vocal snow @sick birch Thanks to both of you ^^

quick gust
#

ghost message?

quick gust
echo wasp
echo wasp
#

do i just do this? ```py

@commands.Cog.listener
async def on_member_join(self, member: discord.member):
role = member.guild.get_role(904216437399355402,role2, role3, role4, role5, role6, role7, role8, role9, role10)
await member.add_roles(role)``` ???

shadow wraith
#

how do you attach a file into the bot's message

quick gust
#

.send() has a file kwarg

slate swan
shadow wraith
#

why do i get this error

Command raised an exception: IsADirectoryError: [Errno 21] Is a directory: 'images/'

#

im trying to upload a file to a msg

slate swan
#

whats your code

shadow wraith
#

its kinda long but ill show the important part

#
elif taiwan_q.content.lower() == "n":
                await ctx.send("you passed that question, next question")
                await asyncio.sleep(0.5)
                await ctx.send(
                    "is this dwayne the rock johnson? (y/n)",
                    file=disnake.File(fp = "images/",filename="thewok.jpeg"),
                )
                thewok_q = await self.bot.wait_for(
                    event="message", timeout=60.0, check=check
                )
slate swan
#

you are using disnake?

shadow wraith
#

mhm

slate swan
#

I never used it 🤷dont know how I could help ya here

shadow wraith
#

its just a fork

slate swan
#

whats disnake.file do

fast vortex
#

It's the same as dpy, this error would occur in dpy too

shadow wraith
#

its like discord.File i think or something

#

im trying to attach a file to a msg

fast vortex
slate swan
fast vortex
#

Mhm

shadow wraith
#

@fast vortex i got a Command raised an exception: FileNotFoundError: [Errno 2] No such file or directory: 'thewok.jpeg' even tho the file exists

fast vortex
#

Full path

slate swan
shadow wraith
fast vortex
#

images/thewok.jpeg

shadow wraith
#

in which arg should i put that in lol

fast vortex
#

Fp

shadow wraith
#

fp?

slate swan
#

anyone know how I could host my bot?

fast vortex
#

Mhm

fast vortex
slate swan
#

I know, but like I have 0 clue how to set it up

fast vortex
#

Here are some good ones

fast vortex
slate swan
#

those are just sites, not how to set it up

fast vortex
#

A tutorial on how to set it up using the service you choose from those sites

slate swan
#

can anyone help me can run interactions on my device

#

whats wrong

echo wasp
#

hmm why do i get this error (picture) code: py @commands.Cog.listener() async def on_member_join(self, member): if member.guild.id == 902404450432483378 : return role1 = member.guild.get_role(933104091066941530) role2 = member.guild.get_role(936481481113632839) role3 = member.guild.get_role(936712347211419708) role4 = member.guild.get_role(936712664950931476) role5 = member.guild.get_role(842254098266718219) role6 = member.guild.get_role(842253873376264222) role7 = member.guild.get_role(842254463309316136) role8 = member.guild.get_role(842260259417489448) role9 = member.guild.get_role(842260429044842572) role10 = member.guild.get_role(893308041699680337) role11 = member.guild.get_role(816838497159610369) role12 = member.guild.get_role(826636738306506794) role13 = member.guild.get_role(841144860966125568) roles = [role1, role2, role3, role4, role5, role6, role7, role8, role9, role10, role11, role12, role13] await member.add_roles(roles)

boreal ravine
#

do *roles

#

that way you unpack all the values in the list

unkempt canyonBOT
#
NEGATORY.

No documentation found for the requested symbol.

boreal ravine
#

!d discord.InteractionResponse.defer put this inside the button if you aren't sending anything @cedar smelt

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.
boreal ravine
#

!d discord.Interaction.response use this to get the InteractionResponse class

unkempt canyonBOT
#

Returns an object responsible for handling responding to the interaction.

A response can only be done once. If secondary messages need to be sent, consider using followup instead.

boreal ravine
echo wasp
boreal ravine
#

👍

#

👍

maiden fable
#

U gotta use global variables ;-;

#

Or smth

tidal hawk
#

put index as class afftribute

#

self.index = 0

maiden fable
#

Or that, yea

tidal hawk
#

why is that class in your function

visual island
#

!e

a = 1

def foo():
  b = a
  b = 2
foo()
print(a)
unkempt canyonBOT
#

@visual island :white_check_mark: Your eval job has completed with return code 0.

1
visual island
#

oh

#

yeah you should global it / use botvar

maiden fable
tidal hawk
#

move it xd

maiden fable
#

Oh, nvm

warm forum
#

Is there a way my bot can store discord member nickname in a variable who just use call the bot?

tidal hawk
#

indentation of buttons is wrong

echo wasp
#

So when i was working on my bot i added a new command to the main file i am running it twice and neither of the welcome messages work without an error in the console the leave message is the expect same except it does on member remove instead of join so why is it happening and how do i fix it i never even messed with it and didn't mess with perms either.

warm forum
echo wasp
# echo wasp So when i was working on my bot i added a new command to the main file i am runn...
@commands.Cog.listener()
    async def on_member_join(self, member: discord.member):
        if member.guild.id == 902404450432483378 : return
        channels = member.guild.channels
        for channel in channels:
            if ('welcome' in channel.name.lower()) or ('joins' in channel.name.lower()): #or ('testing' in channel.name)
                await channel.send(f"A new soldier named, {member.mention} , has joined **Bro's SMP War!** Make sure to check out [#806264072454537267](/guild/267624335836053506/channel/806264072454537267/) and [#899440312223662121](/guild/267624335836053506/channel/899440312223662121/) first before doing anything else.")

    @commands.Cog.listener()
    async def on_member_remove(self, member: discord.member):
        if member.guild.id == 902404450432483378 : return
        channels = member.guild.channels
        for channel in channels:
            if ('leave' in channel.name.lower()) or ('goodbye' in channel.name.lower()) or ('graveyard' in channel.name.lower()):
                if isinstance(channel, discord.TextChannel):
                    await channel.send(f"**{member}** left the server because they suck :+1:")

obsidian ledge
#

how to add a cooldown on a command

tidal hawk
warm forum
tidal hawk
slate swan
#

What to put here?

#

!d discord.Activity.assets

unkempt canyonBOT
#

A dictionary representing the images and their hover text of an activity. It contains the following optional keys:

large_image: A string representing the ID for the large image asset.

large_text: A string representing the text when hovering over the large image asset.

small_image: A string representing the ID for the small image asset.

small_text: A string representing the text when hovering over the small image asset.

slate swan
#

What to put on the large_image

echo wasp
#

can someone help with my issue?

tidal hawk
#

I think it just returns dictionary and you meed to access the value with key: dict[key]

slate swan
tidal hawk
slate swan
#

no running event loop

#

The code is fine but i think something isn't right in backend

vocal snow
#

Could you send the full traceback please?

#

Oh nvm I see it

earnest ingot
pine crown
#

how to make it so that if the user does not have administrator perms, it sends a message

vocal snow
obsidian ledge
earnest ingot
vocal snow
#

!d discord.ext.commands.cooldown

unkempt canyonBOT
#

@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")

A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").

If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.

A command can only have a single cooldown.
vocal snow
#

@obsidian ledge ^ you can put this decorator on a command

obsidian ledge
#

alr

#

thanks

pine crown
#

how to make it so tht if a discord user does not have administrator perms, it messages you do not have permission to do thart

quick gust
#

use the has_permissions decorator and handle the error it raises (MissingPermissions)

quick gust
#

!d discord.ext.commands.has_permissions

unkempt canyonBOT
#

@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.

Note that this check operates on the current channel permissions, not the guild wide permissions.

The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").

This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
vocal snow
#

you can override the _init_

#

what do you mean?

pine crown
vocal snow
#
class Buttons(discord.ui.View):
    def __init__(self, ctx, *args, **kwargs):
        self.ctx = ctx
        super().__init__(*args, **kwargs)
vocal snow
#

just change the parameters of _init_ as per your needs

#

check the part about class instantiation

pine crown
quick gust
#

use the on_error event and isinstance

vocal snow
#

Yes (assuming Reminders is a module)

velvet tinsel
pine crown
velvet tinsel
#

Stop

pine crown
velvet tinsel
pine crown
tidal hawk
#

add “super().init()”

boreal ravine
#

call super in your __init__ method if you wanna access discord.ui.View's properties/methods/attributes

orchid bay
#

Hi

boreal ravine
#

but I prefer putting the attributes below super()

boreal ravine
orchid bay
#

Can u give me free nitro

#

Please

boreal ravine
#

👍

warm forum
#

hey guys how can i restrict some specific word to a chennel. Except those words others words or sentence will be deleted by my bot?

slate swan
#

!d discord.on_message use this event to check messages

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.
severe field
#

How to send video file?

slate swan
#

!voeceverify

unkempt canyonBOT
#

You are not allowed to use that command.

tidal hawk
#

Check OOP tutorials/docs

warm forum
#

hey how can i tell my bot to send message to a specific channel if a event occur

quaint scaffold
unkempt canyonBOT
#
Certainly not.

No documentation found for the requested symbol.

quaint scaffold
#

!d discord.ext.commands.Bot.get_channel

unkempt canyonBOT
severe field
#

How to check if current message is in nsfw channel?

warm forum
#

how can I tell my bot to reply in a specific channel?

unkempt canyonBOT
#

is_nsfw()```
[`bool`](https://docs.python.org/3/library/functions.html#bool "(in Python v3.9)"): Checks if the channel is NSFW.
quick gust
#

ah not the ()

feral halo
#

i think he wanna reply to specific message

#

i think using a message id is also good

#

i mean for channel you use <#> for user you use <@> but for message idk what to use 😭

#

do you have any idea how to

boreal ravine
#

how do I check if a command has an is_nsfw check?

fervent shard
#

help?py @bot.event async def on_message(message): if 'wfl' in message.content: await message.add_reaction('🇼') await message.add_reaction('🇫') await message.add_reaction('🇱')it doesnt work.

fervent shard
fervent shard
boreal ravine
#

Try using the unicode value

fervent shard
boreal ravine
#

the unicode value of the emojis, 🇼 = \U0001f1fc etc

pine crown
#

how to make it so that if the user does not have administrator perms and run a command, it sends a messgae

boreal ravine
#

w

pine crown
pine crown
fervent shard
fervent shard
quick gust
unkempt canyonBOT
#

isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.

Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
pine crown
#

oh

quick gust
#

object will be your error object and classinfo in this case will be the error it raises (MissingPermissions)

pine crown
#

ok

quick gust
#

!d discord.on_error

pine crown
quick gust
pine crown
#

hi

#

okay

quick gust
quick gust
#

takes in error

boreal ravine
fervent shard
boreal ravine
#

👍

pine crown
boreal ravine
lucid forge
#

hey, im trying to make a bot that does certain actions based on the duration people have spent on certain activities using discord presence of users in a guild, how would i go about making it update the information regularly?

quick gust
pine crown
quick gust
#

its MissingPermissions

#

and u gotta import it

pine crown
lucid forge
pine crown
quick gust
#

no

#

from disnake.ext.commands import MissingPermissions

pine crown
quick gust
pine crown
pine crown
#

oh

lucid forge
#

essentially i want to get users' activity data in a loop, i was running it in an async def on_ready() block and that only updated with the information on startup, how do i setup up a loop so that it updates Client.guilds.member.activity data every loop

quick gust
lucid forge
#

ive seen tasks and cogs on a couple stackoverflow threads but im not really sure how to implement it

quick gust
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

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

u can see examples here

lucid forge
#

these examples right? im just not sure how to make my code work in these

quick gust
#

yes these

lucid forge
#

not very good with python i can show you the garbage ive written if that would help

pine crown
# quick gust yes these
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, MissingPermissions):
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await ctx.send(embed=embed)

its not not working

quick gust
#

I've gotta go in a bit

quick gust
#

and see if it errors

pine crown
quick gust
#

outside if statement

lucid forge
#

this is what ive got, thing is client.guilds.members is only assigned at the start of the program, where would i paste the body of this code into that example?

quick gust
slate swan
pine crown
# quick gust can go inside your task
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, MissingPermissions):
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await ctx.send(embed=embed)
  raise error

it dont owkr

quick gust
#

so inside

from discord.ext import tasks

@tasks.loop(seconds=5.0)
async def task_name():
    #here

task_name.start()
lucid forge
slate swan
robust verge
#

I need a code for the discord bot which after typing the command '! Cooldown <number>' will set the slowdown on the text channel where the message was sent for the number of seconds given in '<number>'. If it is set to '0' it will not slow down. If someone wants to write such a code for me, thank you in advance.

slate swan
# pine crown wdy

!e

a = 1
def function():
    if a == 1:
        print("yes")
    raise "no"
function()
a = 2
function()
unkempt canyonBOT
#

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

001 | yes
002 | Traceback (most recent call last):
003 |   File "<string>", line 6, in <module>
004 |   File "<string>", line 5, in function
005 | TypeError: exceptions must derive from BaseException
pine crown
#

ok

slate swan
pine crown
#

how to fix my code

slate swan
pine crown
# slate swan in your case yes

@client.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
await ctx.send(embed=embed)

slate swan
#

what about it?

pine crown
#

its not sending the mssage

#

when the person

#

does not have perms to send

slate swan
#

why not make a special error handler for just that command?

pine crown
#

om

#

g

slate swan
#

on_command_error takes all errors from a command

#

you pasted your whole code on a syntax error?

maiden fable
#

Damn discord changed the colors

pine crown
quick gust
maiden fable
quick gust
#

nice

maiden fable
#

The colors on PC sucks ngl

slate swan
unkempt canyonBOT
#

@error```
A decorator that registers a coroutine as a local error handler.

A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
quick gust
#

true i dont like the green

slate swan
#

show tb

maiden fable
#

Oh rip

#

I'm on Android not iPhone tho

visual island
#

is this py syntax highlighting?

slate swan
#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.

A full traceback could look like:

Traceback (most recent call last):
    File "tiny", line 3, in
        do_something()
    File "tiny", line 2, in do_something
        a = 6 / b
ZeroDivisionError: division by zero

The best way to read your traceback is bottom to top.

• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).

To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.

visual island
#

js

#

js syntax highlighting

slate swan
#

how is that js?

visual island
#

the syntax highlighting

#

🙄

slate swan
#

you go by syntax highlighting and not the actual syntax?

quick gust
#

she is talking about the color being different

slate swan
#

welp gtgpithink

visual island
#

yeah that

quick gust
#

can u even do that

#

yeah

robust verge
#

I need a code for the discord bot which after typing the command '! Cooldown <number>' will set the slowdown on the text channel where the message was sent for the number of seconds given in '<number>'. If it is set to '0' it will not slow down. If someone wants to write such a code for me, thank you in advance.

quick gust
paper vector
#

i want a code that prints the title of the embed whenever an embed is sent.plz help

visual island
#

!d discord.Embed.title

unkempt canyonBOT
visual island
#

it has title attribute

hoary cargo
#

try .edit_original_message

boreal ravine
#

what library are you using?

#

yes

slate swan
#
    bot = interactions.Client(token=TOKEN)
  File "C:\Users\anand\AppData\Local\Programs\Python\Python310\lib\site-packages\interactions\client.py", line 76, in __init__
    self._http = HTTPClient(token=token)
  File "C:\Users\anand\AppData\Local\Programs\Python\Python310\lib\site-packages\interactions\api\http.py", line 337, in __init__
    self._req = Request(self.token)
  File "C:\Users\anand\AppData\Local\Programs\Python\Python310\lib\site-packages\interactions\api\http.py", line 168, in __init__
    self._loop = get_event_loop() if version_info < (3, 10) else get_running_loop()
RuntimeError: no running event loop```
boreal ravine
#

Did you defer?

slate swan
slate swan
#

There is nothing wrong with the code but i keep getting this error

#

And this is the only library used for slash commands
If I'm not wrong...

slate swan
slate swan
#

there are like 10 better libraries

slate swan
slate swan
maiden fable
paper vector
#

can anyone help me i want to print title of embed

async def on_message(ctx):
    try:
        print(ctx.embed.title())
    except:
        None```
slate swan
#

I wasted my time on this one i won't go with this now

paper vector
#

thx

shadow wraith
#

i suggest disnake

slate swan
#

I will get slash commands feature??

slate swan
#

yes, along with buttons, views etc

slate swan
#

okay someone told me ab pycord

#

ik, tons of adverts

#

but if you really check into it, disnake is a better fork

boreal ravine
slate swan
#

What ab hikari?

slate swan
boreal ravine
#

if you wanna use hikari use lightbulb don't use tanjun pls it's too complex for me imo

slate swan
#

yea, tanjun is fire lol

#

so you may use disnake

#

okay

maiden fable
#

@slate swan u need my advice?

#

Code

slate swan
#

in case you wanted to know how hikari-lightbulb works py @info_plugin.command @add_cooldown(10, 2, bucket=UserBucket) @option(name="user",description="Targetted User",required=False,type=Optional[User]) @command( name="avatar",description="View user's avatar ",aliases=["av", "pfp"]) @implements(PrefixCommand, SlashCommand) async def av_cmd(context: Context) -> None:

everything works with decorators & you can implement slash and normal commands together

maiden fable
#

U need to use interaction.response.send_message() first

#

???

#

Hmm

#

I don't remember the fix tbh

#

I made a Paginator for ephemeral message

slate swan
slate swan
#

i can send an invite if you need

#

sure

#

tysm

coral canyon
#

hello!

#

im facing a problem, or well, multiple, the first would be that im finding the discord.py documentation really hard to comprehend

#

2nd issue, probably given by the first, is that im trying to make a bot that send me a jpg from my pc in a channel whenever it detects movement from the camera. the camera part is set up, as is a 5 delay timer and writing the jpg. im not succeeding in making the discord bot send me the jpg, and im having trouble understanding how to use/what i should use instead of client.run since it stops all the code after it

#
                frame_jpg = cv.imwrite('feed.jpg', frame2)
                pn.send_text('prova')
                delay = time.time()
                channel = client.get_channel(ID)
                with open('feed.jpg', 'rb') as f:
                    picture = discord.File(f)
                    async def send_file():
                        await channel.send(file=discord.File(frame_jpg))
                    client.run(TOKEN)
visual island
#

use .start() with asyncio.create_task()

pine crown
#
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, MissingPermissions):
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await ctx.send(embed=embed)

why not working

slate swan
pine crown
slate swan
slate swan
slate swan
pine crown
slate swan
pine crown
slate swan
#

oh

slate swan
pine crown
# slate swan oh

but the error coms in the console though(the missing permissions)

slate swan
#

are you in a cog?

pine crown
slate swan
#

hm

pine crown
#

do u want to see my full code

#

!Paste

unkempt canyonBOT
#

Pasting large amounts of code

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

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

coral canyon
slate swan
slate swan
#

any code after the run method would not be executed

minor bobcat
#

hey does some1 know something bout discord buttons cause i tried discord_components but the buttons couldnt react

minor bobcat
#

ye ik

#

ive heard ppl say its bad

#

but what do i use then

minor bobcat
arctic wraith
#

any fork or hikari

minor bobcat
slate swan
minor bobcat
arctic wraith
slate swan
slate swan
minor bobcat
#

yes i asked in the official server they said upgrade to 2.0 but that one doesnt work

arctic wraith
minor bobcat
coral canyon
slate swan
minor bobcat
#

so
pip install nextcord

arctic wraith
#

personally I'd say at this point in time probably disnake > nextcord, but nextcord's doing some hot stuff for their 3.0 (iirc) release

minor bobcat
minor bobcat
#

ty

#

ill take a look!

arctic wraith
#

they're very similar syntax-wise

minor bobcat
#

do i have to....

vocal snow
minor bobcat
#

instead of nextcord

vocal snow
#

i thought you wre using disnake

minor bobcat
#

no nextcord

#

idk for sure

slate swan
minor bobcat
#

but what do u guys like more

vocal snow
#

yes, hence the eyes

slate swan
#

I'm totally biased pithink

minor bobcat
#

but the difference between normal and disnake and nextcord

minor bobcat
#

the difference

pine crown
slate swan
minor bobcat
#

so thats how u make buttons

minor bobcat
#

but the way its setup isnt different

#

i dont have to rewrite

slate swan
arctic wraith
# coral canyon im not making a function tho, like all the code is inside a while and a nested f...

what I'd probably recommend is something like

import asyncio
import discord  # /whatever you use

loop = asyncio.get_event_loop()
client = discord.Client(..., loop=loop)

async def check_cam():
    await client.wait_until_first_connect()  # ensure the bot is running before the function continues
    while True:
        ...  # do your image stuff here
        await asyncio.sleep(5)  # wait 5 seconds before trying again

loop.create_task(check_cam())  # start check_cam as a background task

bot.run(<token>)
#

ish

arctic wraith
#

probably just that their cam movement detection code is all at module level (in the bot file)

#

which won't work with a bot

tidal hawk
#

Do you want to change the ephemeral message after clicking the button.. or when?

coral canyon
#

am i allowed to share big snippets of code here?

pine crown
#
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await ctx.send(embed=embed)

why this not working ..):

slate swan
#

is rillrate dead?

arctic wraith
arctic wraith
#

probably best off as two separate processes

slate swan
tidal hawk
#

and interaction.response.edit_message() doesn't work? @cedar smelt

vocal snow
vocal snow
#

error = getattr(error, 'original', error)
``` you can add this to use the original exception
pine crown
#
@client.event
async def on_command_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    error = getattr(error, 'original', error)
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await ctx.send(embed=embed)

like this?

vocal snow
#

no

lucid forge
#

is there any way to ban a user automatically, without any input?

vocal snow
tidal hawk
#

Your welcome, I was stuck there yesterday aswell :D

lucid forge
# tidal hawk With mind?

with mind? idk what that means but the bot would determine if the user is to be banned or not, and then bans automatically, no need for anyone to type any commands

final iron
#

Do your logic and then ban or don't ban them

boreal ravine
#

py-cord, disnake, nextcord have easier syntaxes than lightbulb

slate swan
#

^^

coral canyon
lucid forge
pine crown
# vocal snow ```py error = getattr(error, 'original', error) ``` you can add this to use the...
@client.event
async def on_command_error(ctx, error):
  error = getattr(error, 'original', error)
  if isinstance(error, commands.MissingPermissions):
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await ctx.send(embed=embed)

still doesnt work ):
do u want my full code so u can chec k if anything else is blocking it

tidal hawk
final iron
unkempt canyonBOT
#

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

Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.ban "discord.Guild.ban").
lucid forge
lucid forge
#

!d discord.Member.kick

unkempt canyonBOT
#

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

Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.kick "discord.Guild.kick").
lucid forge
#

i could replace the * with the userID right?

#

thanks :D

tidal hawk
#

Member object

lucid forge
#

oh okay thank you

slate swan
tidal hawk
#

yeah

#

ik

slate swan
#

you use the kick method on the Member object

tidal hawk
#

Mhm

#

Didnt see member.kick

slate swan
final iron
#

What?

tidal hawk
#

Yeah it was my bad bro lmao

cloud dawn
#

!d discord.Member.kick

unkempt canyonBOT
#

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

Kicks this member. Equivalent to [`Guild.kick()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.kick "discord.Guild.kick").
tidal hawk
#

HAHA

pine crown
# vocal snow does it raise the exception?
PexiBot is ready.
Ignoring exception in slash command 'ban':
Traceback (most recent call last):
  File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1346, in process_application_commands
    await app_command.invoke(interaction)
  File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 574, in invoke
    await self.prepare(inter)
  File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\base_core.py", line 205, in prepare
    if not await self.can_run(inter):
  File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\base_core.py", line 524, in can_run
    return await async_all(predicate(inter) for predicate in predicates)  # type: ignore
  File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 561, in async_all
    for elem in gen:
  File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\base_core.py", line 524, in <genexpr>
    return await async_all(predicate(inter) for predicate in predicates)  # type: ignore
  File "C:\Users\e\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 2068, in predicate
    raise MissingPermissions(missing)
disnake.ext.commands.errors.MissingPermissions: You are missing Ban Members permission(s) to run this command.

says this

tidal hawk
#

Listen to bosses

vocal snow
cloud dawn
#

!d disnake.ext.commands.Bot.on_slash_command_error

unkempt canyonBOT
#

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

The default slash command error handler provided by the bot.

By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for slash command error.
vocal snow
# unkempt canyon

@pine crown ^ you'd use this instead of on_command_error since it seems you have an application command

pine crown
#

ok

pine crown
pine crown
grim oar
#

😼

vocal snow
#

Nova is a disnake contributor so he can tell you

pine crown
#

ok

grim oar
#

Yes

pine crown
#

hi

grim oar
#

Hi

pine crown
#

help me

grim oar
#

ok

pine crown
#
await on_slash_command_error(interaction, exception)

i put this inside application command?

grim oar
#

Idk try it and see

pine crown
#

h

pine crown
grim oar
#

looks like a decorator

pine crown
#

wat

grim oar
#

idk

pine crown
#

ok

vocal snow
pine crown
slim ibex
#

!d disnake.ext.commands.Bot.on_slash_command_error

unkempt canyonBOT
#

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

The default slash command error handler provided by the bot.

By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.10)") however it could be overridden to have a different implementation.

This only fires if you do not specify any listeners for slash command error.
final iron
#

You're over riding the default on_slash_command_error

pine crown
#
@client.event
async def on_slash_command_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await ctx.send(embed=embed)
#

ok

grim oar
#

0 arg is interaction not ctx

pine crown
#

ok

#
@client.event
async def on_slash_command_error(interaction, error):
  if isinstance(error, commands.MissingPermissions):
    embed=disnake.Embed(color=0xb30000, title="Error", description="You do not have the permissions to use this command.")
    await interaction.send(embed=embed)
#

thank

#

you

grim oar
#

Np, your charge is 2 dollars

pine crown
#

😮

pine crown
grim oar
#

ty

#

btw also raise error with an else, that among us may eat the errors

pine crown
#

lol

#

ok

hoary cargo
pine crown
#

i know a pythongus

grim oar
#

shiki

pine crown
hoary cargo
quick gust
grim oar
#

😼

pine crown
#

what is with that emoji and you

slate swan
#

Hi all, just a quick query in regards to discord bots/python libraries... I want to restart my python learning, plenty of resources to do so but I am a bit confused around the libraries now..

As of august 2021 discord.py was discontinued, is this still safe to use or would you recommend using a different library such as nextcord or enhanced-discord.py?

grim oar
#

disnake is like dpy use that

slate swan
#

You could be a winner with your profile pic...

hoary cargo
#

You can still use dpy if you plan having a private bot in your server without any intent of growing and if you won't use slash commands or /and buttons

grim oar
#

inport discord as disnake

hoary cargo
pine crown
quick gust
#

you can go with a fork if you wanna continue the same format as dpy (i prefer disnake), otherwise use a different library like hikari which has a very different format than dpy (obviously)

hoary cargo
#

Yeah but it's not an official release on PyPI though

boreal ravine
#

either use a fork or nextcord, enhanced-dpy

#

e-dpy pretty complete

hoary cargo
#

Disnake is ur way to go

slate swan
#

go on I'm sold, too many anime fans recommening disnake, so how could I not 😛 thank you all ❤️

boreal ravine
#

||(weebs)|| 👍

hoary cargo
#

raidenhmmmm I didn't watched any anime for a year

pine crown
#

idont even know what anime is

hoary cargo
#

Questionable

pine crown
#

what is that poopo gif

slate swan
#

If you're an anime fan, hikari exists creepy

arctic wraith
pine crown
#

ok

arctic wraith
#

also yeah hikari is extremely weeb

#

I'm all for it tho haha

pine crown
#

i have coconut canister

hoary cargo
#

In what sense is very weeb tho

slate swan
#

Not the library, but the devs are

arctic wraith
#

hikari is jp for light
most of their "official" extensions have jp names
most of their emotes are anime-related
among a couple other things

slate swan
#

By most, you mean tanjun

arctic wraith
#

but yeah as far as I'm concerned it's all in good fun

#

hikari-miru is too

slate swan
#

It is really fun

#

Miru is not an official extension, it's just like discord-components in Discord.py

#

!pip hikari-miru

arctic wraith
#

ah yeah fair

unkempt canyonBOT
arctic wraith
#

think I'll get around to making a bot in hikari sometime soon

#

have been meaning to do so for a while

slate swan
#

It's a library worth trying

#

Im rewriting my bot in hikari

arctic wraith
#

yeah purely judging by source code I think it's the best python lib out there atm

#

as in discord api wrapper, that is

slate swan
#

async def on_message(message): if wordfilter in message.content: await message.delete()
wordfilter = ['bad','bot']

Why it delete all message if i start !help arg1

slate swan
pine crown
slate swan
#

!e if ['a','b'] in "ab":
print(1)

unkempt canyonBOT
#

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

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: 'in <string>' requires string as left operand, not list
slate swan
#

see the error

tidal hawk
slate swan
slate swan
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
cloud dawn
boreal ravine
gaunt ice
#

!pip keyboard

unkempt canyonBOT
slate swan
velvet tinsel
#

im going to an animecon/gamingcon/comicon...? on saturday

#

tbh idk what it's even called LOL

velvet tinsel
maiden fable
#

Calendar as in?

#

So like, this way, the user will be able to input important dates, events and stuff?

spring flax
#

the calendar app exists

maiden fable
#

But yea, u correct

spring flax
#

i mean I guess you can make a command...

#

but, it's less efficient than using a calendar app

maiden fable
#

I don't really think how that's gonna be possible tbh. It would look seriously ugly since codeblocks and those fuck up since the screen size if different for all the devices

maiden fable
honest vessel
#

cache them? ^

maiden fable
# honest vessel cache them? ^

Yea... but how I'm picturing it, a calendar command would be the same as a remind command, but just with a picture to show the events, right?

obsidian ledge
#

how do i edit a channel's topic

honest vessel
#

channel.edit() (just guessing)

maiden fable
obsidian ledge
#

do u need to import anything

maiden fable
#

!d discord.TextChannel.edit has a topic kwarg

unkempt canyonBOT
#

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

Edits the channel.

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

Changed in version 1.3: The `overwrites` keyword-only parameter was added.

Changed in version 1.4: The `type` keyword-only parameter was added.

Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
honest vessel
#

@maiden fablei dont know what calendar he wants but i was just thinking if first time command is run for that date it will just take long time ofc processing, but he can then cache it for next one who checks that day

maiden fable
#

Yea

honest vessel
#

u can just do .calendar 2022-02-02

#

timedelta

maiden fable
#

You know... people didn't care about a remind command too

#

But your idea is doable tbh

#

I would love to help u make this command if u want to make something like this (:

honest vessel
#

so tell me how this calander gonna contain and be used @cedar smelt

maiden fable
#

I got a rough image in mind tbh

#

!d calendar is also there to help you 👀

unkempt canyonBOT
#

Source code: Lib/calendar.py

This module allows you to output calendars like the Unix cal program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. Parameters that specify dates are given as integers. For related functionality, see also the datetime and time modules.

honest vessel
#

i mean is it just going to display dates n dates of a selected month?

maiden fable
#

Uhhh nope

#

Actually @cedar smelt, I like this idea of yours!

#

This can just become more of an upgraded version of a simple remind command

honest vessel
#

@cedar smeltcan u explain how u vision it like what will it contain and show

maiden fable
#

I would love to help you implement something like this yourself since this is your idea (:

honest vessel
#

draw in paint 😄

#

so i can see how u thinking

maiden fable
#

Haha well I got a raw idea of how the command would be looking/working

#

We can use something like .event set <date> <event>

#

We add it to the database

#

And we generate the calendar image and store it in a folder and the image name could be the Author's ID(?)

#

And whenever someone runs the set command, a new image with the updated calendar will be shown

honest vessel
#

image name should be unique like the messageID

maiden fable
honest vessel
#

and u just add discordID as creator in row of db

maiden fable
#

We can simply use discord.File(f"{message.author.id}_{month}.png") and use a try except to check for any errors in case a file with that name isn't present

honest vessel
#

oh each users will have their own calendar

maiden fable
#

Yup

honest vessel
#

command and db would be easy n fast to create

maiden fable
#

And whenever a month ends, the photo of that month gets deleted

#

There are numerous ways to do the same thing

honest vessel
#

and clears his db of that month save HDD

slate swan
#

i need help.

maiden fable
#

Yea

#

Sure what happened

slate swan
#

i wanna make so the bot takes all the commands from the folder general moderation and economy and adds it as commands

maiden fable
#

!d discord.ext.commands.Bot.add_command

unkempt canyonBOT
#

add_command(command)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.

This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.

Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/master/api.html#discord.ClientException "discord.ClientException")
slate swan
#

ok

#

so after should i just bot.add_command(‘’)

#

the command i made?

#

nvm

cloud dawn
#

@maiden fableYou got experience with numpy?

maiden fable
slate swan
#

pls help @maiden fable it does not work..

#

can u do it without cogs

#

or

#

idk

cloud dawn
#

Why would you want to do it without cogs?

slate swan
#

idk

#

nvm imma just do it in js 😔

cloud dawn
#

js is harder, they do got more examples.

slate swan
#

yeah

#

js is so hard

cloud dawn
#

Compiled language 😔

cloud dawn
unkempt canyonBOT
slate swan
#

OMG THANKS SO MUCH

#

oh wait

#

oh

leaden jasper
#

how to wait for reaction add and a message?

final iron
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**...
arctic wraith
#

you're using disnake right?

devout iris
#

Can i make that?
Token = [token1, token2, token3, ....]
bot.run(Token)

honest vessel
#

@cedar smeltmaybe this ```py
def cog_unload(self):
self.service.stop()

self.service.start() in ur class init
#
    @tasks.loop(seconds=120)
    async def service(self):
``` service = task
tidal hawk
devout iris
honest vessel
#

but codes are the same lol

devout iris
#

Yes i know codes will be same :/

honest vessel
#

so whats the point? 😄

devout iris
#

i was have an opinion a few monents ago but i forgot it SMH

#

🤦🏻🤦🏻🤦🏻

tidal hawk
#

for token in tokens:
bot.run(token)

#

idk if it actually works

honest vessel
#

its a 50/50

#

but prob it just uses last token 😛

arctic wraith
tidal hawk
#

What if

slate swan
#

no, it wont work

arctic wraith
#

I think it'll run the first bot

slate swan
#

the first bot will run

arctic wraith
#

then wait until you close the first bot, then launch the next

tidal hawk
#

What if you create multiple threads and on each thread you run client

arctic wraith
#

etc.

slate swan
honest vessel
devout iris
#

What about if i do a few bot.run() ??

honest vessel
#

lool

tidal hawk
#

No

devout iris
#

Smh

arctic wraith
#

what about you just use a singular bot, lol

slate swan
#

you can, use bot.start() to run multiple bots in the same file

honest vessel
#

what u can do is put token as argv and run script with tokens as argvs

#

and have a script that runs them bots

devout iris
honest vessel
#

@arctic wraithhe had an opinion!

devout iris
#

maybe i can use different bots in different servers

honest vessel
#

whats the point? u want diffrent avatars depend on server?

devout iris
#

Not only avatars actually

honest vessel
#

(would be nice if discord allowed multi avatars that could be set by serverowners)

arctic wraith
arctic wraith
#

yes?

devout iris
#

How?

honest vessel
#

what is shards?

arctic wraith
#

e.g. disnake just has an AutoShardedBot iirc

honest vessel
#

@arctic wraithcan u give me brief explanation what shards are?

devout iris
arctic wraith
#

I think it's generally about 1k members per shard?

honest vessel
#

ah nice thanks

tidal hawk
#

What's the right approach for creating a disnake button, which is functional after bot restart

quick gust
#

persistent views, hunter sent a link. Let me find it

honest vessel
#

he uses disnake tho - probally same?

tidal hawk
#

I think the logic is the same

#

Thanks @quick gust

quick gust
arctic wraith
#

yeah the example is the exact same as the one on the disnake repo

quick gust
tidal hawk
#

That's actually amazing

honest vessel
#

ye aint it like discord.py but changed all files with replace("discord, "disnake") 😄 and more features

arctic wraith
#

~ish

quick gust
tidal hawk
#

so discordpy has also buttons/slash commands built in?

quick gust
#

No slash commands

#

Only views

silver magnet
#

im still new to discord.py and i wanted to know if theres any way you can find a user from message context

slim ibex
#

!d discord.Message.author ?

unkempt canyonBOT
silver magnet
#

not the author