#discord-bots

1 messages · Page 665 of 1

tiny ibex
#

That's what he want

maiden fable
#

O

#

discord.Client()

junior verge
#
client = commands.Bot(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
#

Like that?

junior verge
#

Alright lemme see

maiden fable
#

U need to specify a command prefix too

slate swan
#

I tried to insert a pic in tkinter but it kept showing erorr no such file in directory
The problem was when i entered name of the file in code 1 letter was capital

junior verge
tiny ibex
junior verge
#

Ah alright did not know that

lucid prism
#

like
client = commands.Bot(intents=discord.Intents.all(), prefix='!')

tiny ibex
lucid prism
#

ok

junior verge
#

does it need to be a slash

tiny ibex
#

It's totally your wish

slate swan
#

Nvm the translator
I am gonna make a discord bot

tiny ibex
slate swan
#

But i don’t know how to

lucid prism
#

lmao

tiny ibex
lucid prism
#

do this ig

boreal ravine
slate swan
#

K

junior verge
#

client = commands.Bot(intents=discord.Intents.all(), command_prefix='.')
slash = SlashCommand(client, sync_commands=True)
``` that wrong?
slate swan
#

But all of the tutorials are not good

boreal ravine
boreal ravine
#

made by a helper here

slate swan
#

Thnks

#

K

sullen shoal
#

K

tiny ibex
#

This is good ^

junior verge
#

wait does it need to be in all the cogs as well?

boreal ravine
#

k

boreal ravine
tiny ibex
junior verge
#

any idea

#
client = commands.Bot(intents=discord.Intents.all(), prefix='.')
slash = SlashCommand(client, sync_commands=True)
boreal ravine
#

bruh

#

try putting command_prefix first

junior verge
#

I did

#

got the same error

boreal ravine
#

and it isnt "prefix"

junior verge
boreal ravine
junior verge
#

alr

boreal ravine
#

@lucid prism no misleading

junior verge
tiny ibex
#

prefix is not a thing unless you made it yourself

junior verge
tiny ibex
#

Not prefix at all

junior verge
#

Yeah I get that

#

That's not what I meant

boreal ravine
junior verge
#

What do you mean by dunder

boreal ravine
#

the functions

#

with 4 underscores

lucid prism
junior verge
#

In what cog?

boreal ravine
#

init, hash, eq etc

junior verge
junior verge
#

setup?

boreal ravine
junior verge
#

3

#

It's just basic cogs

boreal ravine
#

show full error

junior verge
#

alr

sullen shoal
#

cogs/setup.py

#

what the heck is that

junior verge
#

it's a cog for a going to be setup command

boreal ravine
junior verge
#

something wrong with that or?

#
import discord
from discord.ext import commands 
from discord_slash import SlashCommand
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure 
import datetime

client = commands.Bot(intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)

class Setup(commands.Cog):

    def __init__(self, client):
        self.client = client

    
    @slash.slash(name="setup")
    @has_permissions(administrator=True)
    async def setup(self, ctx):
        embed = discord.Embed(title='Setting everything up!', color=0xe30505)
        await ctx.send(embed=embed, delete_after=5.0)
        await ctx.message.delete()

  

def setup(client):
    client.add_cog(Setup(client))
sullen shoal
#

you should be defining that as a function of your cog

#

alot of stuff is wrong here

boreal ravine
#

hm

sullen shoal
#

and im leaving this to these people, i am done

junior verge
#

it used to work, just when I am trying to get slash commands to work

#

like the code is right but not for slash commands which I want

boreal ravine
#

i mean yout error doesnt make sense at all

junior verge
#

oh

#

welp

boreal ravine
#

cogs shouldnt need a command_prefix arg

boreal ravine
junior verge
#

Yeah

boreal ravine
#

bruh

junior verge
#

uhm?

boreal ravine
#

you dont have command_prefix kwarg

boreal ravine
junior verge
#

How?

sullen shoal
#

damn these guys are still confused lmao

boreal ravine
#

command_prefix="ur prefix", intents=discord.Intents.all()

#

^^

junior verge
#

On what line or?

boreal ravine
sullen shoal
#

they're defining another bot instance instance in a cog. which they shouldn't

junior verge
#

Kinda confused

boreal ravine
junior verge
sullen shoal
#

the entire thing is wrong

boreal ravine
#

in*

junior verge
#
client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)
``` like that
boreal ravine
#

yes

junior verge
#

oh no still getting errors well I have to eat

boreal ravine
#

!intents here

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.

boreal ravine
#

first hyperlink

crisp python
#

As it turns out the Python course I took 10+ years ago does not quite allow me enough retained knowledge to jump into creating a Discord bot. Just found this place, glad it exists!

sullen shoal
#

the examples and the docs are quite nice, those are enough to understand every part of the docs

junior verge
crisp python
#

My goal is to accept /slash commands and use them to specify options to be passed to an external application on a Linux server. A game spawner that will allow the end user to choose the game options and choose from just over 5000 maps, and start the game. I'd like the bot to be able to return some text and perhaps also an image of the map choosen, to the one who issues the command in either DM or chat channel to confirm the game was spawned (the external application was started with the submitted options and map name). Does this sound like an obtainable goal?

sullen shoal
#

i guess you meant slash commands

crisp python
#

I sure did! 🙂

sullen shoal
#

if so, you have to use forks because the maintainer of discord.py lib has decided to not add slash commands

tough lance
#

Provided you can do it

sullen shoal
#

other than that its just python and i believe you know what python is capable of

crisp python
#

Pardon the ignorance, but by forks are you referring to something like "discord-interactions-python".

tough lance
#

You can say.

sullen shoal
#

never heard of it so you might not get any support for it here

#

you should use forks like disnake, nextcord

#

i would say to go with disnake

tough lance
#

^

sullen shoal
#

disnake.dev

crisp python
#

Cool, if the goal is obtainable with Python then it's "back to school" for me to get this done!

sullen shoal
#

the goal sounds easy to achieve to me

crisp python
#

I made a game spawner with PHP that passes values to a shell script which then starts the application. My first PHP project or attempt at PHP ever. I figure if I can get that done then I can get it done with Python as well. You know. What one man can do another man can do (with enough learnings).

#

Thanks for the input!

sullen shoal
#

👍

crisp python
#

I was staring down the list of various laguances to write Discord bots and this was the only I had even a bit of experience with at that time.. ..so I just needed to know it could be done before putting the effort into teaching myself Python (refresher) again.

sullen shoal
#

the entire library is object oriented so be sure to read some articles about python classes and OOP

crisp python
#

I seem to remember in the class I took I had a bit of a hard time organizing in my head what function was passing what data. Scrolling up and down the file trying to figure out how the data was flowing through it. They had us making flow charts with visio I think it was, which helped a bit but it was a pain updating the flow chart with every code change.

#

The approach is a heck of a lot better than the old QBasic top to bottom but sometimes it felt like chasing the white rabbit down the hole, around the corner, and into a warp portal to the next dimension.

maiden fable
#

Hmm

sullen shoal
#

i remember looking at some flow charts once, it was pretty confusing

junior verge
stiff nexus
#

in on_interaction interaction.data returns like {'custom_id': 'name', 'component_type': 2} how do i get it like custom_id: name, component_type: 2

boreal ravine
junior verge
#

alright

stiff nexus
#

how?

boreal ravine
#

i mean play around with it if it returns a dict

slate swan
#

is there a list of permissions for updating channel?

stiff nexus
#

huh

boreal ravine
slate swan
boreal ravine
#

@stiff nexus what type of object does interaction.data return

stiff nexus
#

custom_id and component_type

boreal ravine
#

use the type function on interaction
data

junior verge
#
import discord
from discord.ext import commands 
from discord_slash import SlashCommand
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure 
import datetime

client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)

class Setup(commands.Cog):

    def __init__(self, client):
        self.client = client

    
    @slash.slash(name="setup")
    @has_permissions(administrator=True)
    async def setup(self, ctx):
        embed = discord.Embed(title='Setting everything up!', color=0xe30505)
        await ctx.send(embed=embed, delete_after=5.0)
        await ctx.message.delete()

  

def setup(client):
    client.add_cog(Setup(client))
``` Why don't my slash command pop up
slate swan
#

what are a list of permissions from ctx.channel.set_permissions

boreal ravine
stiff nexus
#

also how do i know that the button worked?

junior verge
#

Because the thing that I want is a message that has been posted, it should have a button and if you press it you will see a message like this

junior verge
#

916304061115035749

junior verge
slate swan
#

Have you already done the buttons? And what library are you using?

wanton veldt
#

Its possible to make a restart command on python?

tawdry perch
#

restart in what way?

wanton veldt
#

when i am doing .restart it will shutdown the bot and then turn it back on @tawdry perch

#

thats what i have

manic wing
unkempt canyonBOT
#

os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.

On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
tawdry perch
#

Gotta make up this feature

wanton veldt
#

ty

#

@manic wing can i dm you?

manic wing
#

oh kayle is here, i have to be esoteric. do this - os.system(f"taskkill /F /PID {os.getpid()} &&{python:='python' if os.system('python') else 'python3'} {os.cwd()}/{__file__}") if discord__version__ else True not False

manic wing
wanton veldt
manic wing
#

not really but whatever

stiff nexus
sullen shoal
#

dumb code maybe

sullen shoal
#

else True not False tf

slate swan
#

For a user it's

user: discord.Member
```Is there one for a channel?
manic wing
manic wing
#

because obviously names dont matter according to kayle

slate swan
#

Typing is not defined

boreal ravine
#

import it

manic wing
#

¯_(ツ)_/¯

rare saddle
#

How to make it so that the message has been replaced for clicking on the button 101?

wanton veldt
tawdry perch
slate swan
#
AttributeError: module 'discord' has no attribute 'Channel'
``````py
@commands.command()
async def poll(self,ctx,channel: typing.Union[discord.Channel], *,question):
tawdry perch
#

discord.TextChannel

slate swan
#

Thankyou

#

How do I make this be at the bottom like a footer?

poll_embed = error_embed = discord.Embed(title="Poll", color=0xD22C45, description=f"{question}")
poll_embed.set_footer(name=ctx.author.name, icon_url=ctx.author.avatar_url)
manic wing
#

what you screenshotted isnt this

slate swan
#

oh yeah sorry it was author before which is what the screenshoted is then I changed it to footer which didn't work

manic wing
#

looks fine :O

slate swan
#

Yeah but as there a way for that to be at the bottom instead of the top?

manic wing
#

yes. with footer.

#

btw in set_footer its text= not name=

#

to set the text

#

!d discord.Embed.set_footer

unkempt canyonBOT
#

set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.

This function returns the class instance to allow for fluent-style chaining.
slate swan
#

ah ok thankyou

sonic flax
#

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

junior verge
#
import discord
from discord.ext import commands 
from discord_slash import SlashCommand
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure 
import datetime

client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
slash = SlashCommand(client, sync_commands=True)

class Setup(commands.Cog):

    def __init__(self, client):
        self.client = client

    
    @slash.slash(name="setup")
    @has_permissions(administrator=True)
    async def setup(self, ctx):
        embed = discord.Embed(title='Setting everything up!', color=0xe30505)
        await ctx.send(embed=embed, delete_after=5.0)
        await ctx.message.delete()

  

def setup(client):
    client.add_cog(Setup(client))

Why doesn't this slash command pop up

slate swan
#

Hello

tawdry perch
#

Hi

slate swan
#

i need help

tawdry perch
#

Ask away and someone might help

slate swan
#
@commands.has_role("Bot")
async def reroll(ctx, channel : nextcord.TextChannel, id_ : int):```
IN THE 3RD LINE
!reroll #channel
I DONT WHAT ID I HAVE TO USE THERE
CAN SOMEONE TELL ME
#

@tawdry perch

tawdry perch
#

?

slate swan
tawdry perch
#

I don't have time to explain atm

slate swan
#

wdym

slate swan
quick gust
#

what is this supposed to mean

wanton veldt
#
@client.command()
@commands.is_owner()
async def restart(ctx):
    shutdown_embed = discord.Embed(title='Bot Update', description='I am now Restarting. See you later. BYE! :slight_smile:', color=0x8ee6dd)
    await ctx.channel.send(embed=shutdown_embed)    
    await ctx.bot.logout()
    await client.login("token", client=True)

@restart.error
async def restart_error(ctx, error):
    if isinstance(error, MissingPermissions):    
        await ctx.send("This command is `OWNER` only. You are not allowed to use this. Try not to execute it another time.")
``` why the restart.error command dosent work?
grand yew
#

Anyone who sell jobs

#

Not sure if saying this is allowed

manic wing
#

!rule 9

unkempt canyonBOT
#

9. Do not offer or ask for paid work of any kind.

slate swan
#

I made this help command but when I run the command the bot doesn't send anything nor do I get any errors?

    @commands.command()
    async def help(self,ctx):
        with open('config.json') as f:
            data = json.load(f)
    
        valid_user = False

        for role_id in data["staff-roles"]:
            try:
                if ctx.guild.get_role(role_id) in ctx.author.roles:
                    valid_user = True
            except:
                pass

        if valid_user or ctx.author.guild_permissions.administrator:
            staff_help_embed = discord.Embed(title="Staff - Help", color=0xD22C45, description="Here is the full list of all the commands you can run.")
            staff_help_embed.add_field(name="Ping", value="Checks for bots latency. `.ping`")
            staff_help_embed.add_field(name="Clear", value="Deletes a specific amount of messages in the channel you are in. `.clear|c|purge|p <amount>`")
            staff_help_embed.add_field(name="Poll", value="Starts a poll in specfied channel with specified question. `.poll <channel> <question>`")
            staff_help_embed.add_field(name="Kick", value="Kicks a user from a server. `.kick|k <user> <reason>`")
            staff_help_embed.add_field(name="Ban", value="Bans a user from a server. `.ban|b <user> <reason>`")
            staff_help_embed.add_field(name="Config", value="Shows all avaliable configuration commands. `.config`")
            staff_help_embed.add_field(name="Help", value="Shows this command. `.help`")

        else:
            help_embed = discord.Embed(title="Help", color=0xD22C45, description="Here is the full list of all the commands you can run.")
            help_embed.add_field(name="Ping", value="Checks for bots latency. `.ping`")
            help_embed.add_field(name="Help", value="Shows this command. `.help`")
junior verge
#
@commands.command()
    @has_permissions(administrator=True)
    async def setup(self, ctx):
        embed = discord.Embed(title='Setting everything up!', color=0xe30505)
        await ctx.send(embed=embed, delete_after=5.0)
        await ctx.message.delete()
        ```
How to make it like if this happend then do that like a whole new embed with buttons etc but after this happend
junior verge
#

Alright like I want this embed to show yeah it deletes after 5s now I want just something else to happen while that happens as well but in the same command

manic wing
unkempt canyonBOT
#

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

Sends a message to the destination with the content given.

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

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

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

I already found what I needed

#
import discord
from discord.ui import Button, View
from discord.ext import commands 
from discord.ext.commands import MissingPermissions, has_permissions, CheckFailure 
import datetime
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType, component



class Setup(commands.Cog):
    
    def __init__(self, client):
        self.client = client

    
    @commands.command()
    @has_permissions(administrator=True)
    async def setup(self, ctx):
        embed = discord.Embed(title='Setting everything up!', color=0xe30505)
        await ctx.send(embed=embed, delete_after=5.0)
        await ctx.message.delete()
        em = discord.Embed(title='Get your 1 use invite here!', description="Press the green button to receive a 1 use invite link",color=0x32cd32)
        
        await ctx.send(embed=em,
            components=[
                [Button(style=ButtonStyle.green, label="Invite Link"),
                 Button(style=ButtonStyle.red, label="Admin Panel")]
            ],
        )
        res = await client.wait_for("button_click")
        if res.channel == ctx.message.channel:
            await res.respond(
                type=InteractionType.ChannelMessageWithSource,
                content=f"{res.component.label} <@{ctx.author.id}> Check your dms!"
            )



  

def setup(client):
    client.add_cog(Setup(client))
``` Why doesn't this work...
velvet tinsel
#

hello

#

have you tried pip?

slate swan
slate swan
#

How do I add reaction?

limpid thicket
# slate swan

It should be await message.add_reaction(":white_check_mark:")

limpid thicket
#

No problem.

cloud tundra
#

Ayo
Does anyone know how i can send a message (ctx.send) from inside a synchronous function?

cloud tundra
#

is there anyway to somehow fix this?

remote current
#

what's stopping you from putting "async" in front of the function definition?

manic wing
#

nothing doesnt work in an asynchronous function, things dont work in a synchronous function - just make it asynchronous

#

you call it the same, however you just await the coro

#

!d asyncio.create_task || or, if its outside of an async function you use this

unkempt canyonBOT
#

asyncio.create_task(coro, *, name=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.

If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").

The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.

This function has been **added in Python 3.7**. Prior to Python 3.7, the low-level [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future "asyncio.ensure_future") function can be used instead...
cloud tundra
#

yeah, but that leads to another problem
for some reason i cant call the async function from another one

#

im trying to make a queue function for the bot

#

and the bot is sapoused to call the queue function after the music is done playing

#

to do this im using this code :

#

ctx.voice_client.play(source, after = lambda _: queueFunction(ctx))

cloud tundra
manic wing
sick birch
#

you await them

royal jasper
#

How can I give a role to a certain member in a certain guild?

cloud tundra
verbal cairn
#

That ruins the point of it being async

sick birch
manic wing
#

!d discord.Member.add_roles || member.add_role(role) where member is an instance of discord.Member and role is an instance of discord.Role

sick birch
#

members are associated with a guild

unkempt canyonBOT
#

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

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
sick birch
cloud tundra
#

i cant await the function after the lambda

royal jasper
cloud tundra
#

it just says await can not be used outside async function

sick birch
cloud tundra
#

syntax error

verbal cairn
sick birch
#

low chance that it's cached as the gateway servers sends you all the guilds on_connect

cloud tundra
#

yo by the way is there anyway to join some vc or something here

manic wing
sick birch
manic wing
#

show your code ;-;

cloud tundra
#

just a sec

#
@commands.command()
    async def play(self, ctx, *urlNames):

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            ctx.voice_client.play(source, after=lambda _: await queueFunction(ctx))
            
            await playEmbed2(ctx)

            print("User\u001b[36m", ctx.author.name, "\u001b[32mCONNECTED\u001b[37m the bot in server\u001b[36m", ctx.guild.name, "\u001b[37m ")
#

and this is the queueFunction code:

royal jasper
cloud tundra
#
async def queueFunction(ctx):

    if queueList !=[]:

        url = queueList.pop(0)

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            source = asyncio.run(discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS))
            ctx.voice_client.play(source, after = lambda _: await queueFunction(ctx))
          
            await playEmbed2(ctx)
          
            print("User\u001b[36m", ctx.author.name, "\u001b[32mCONNECTED\u001b[37m the bot in server\u001b[36m", ctx.guild.name, "\u001b[37m ")
    
    else:
        return
verbal cairn
#

So confusing

cloud tundra
#

it just syntax errors me

#

that i can not use the await after lambda

verbal cairn
#

Make a function, then call that function instead of using lambda

cloud tundra
#

what do you mean?

#

why would i ?

verbal cairn
#

Also idk why ur awaiting something inside .play()

verbal cairn
cloud tundra
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.

manic wing
#

@cloud tundra you cant use await in lambda. instead just do ```py
def head(async_iterator): return async_iterator.anext()

lambda: head(await queueFunction(ctx) for _ in '_')```

#

should make complete sense ;)

cloud tundra
#

ill try it right now

slate swan
#

how do i add a error handler in a cog just normally?

cloud tundra
verbal cairn
#

But that’s it i think

slate swan
verbal cairn
#

Nah

#

Decorators same in cogs

slate swan
#

alr thx

verbal cairn
cloud tundra
#

then how can i make it play the new song after the one playing right now is done?

verbal cairn
#

But I don’t get what ur trying to do

#

Await ctx.voice_client.play()

cloud tundra
#
after = lambda _: await queueFunction(ctx)
verbal cairn
#

Idk really Bc I haven’t worked with voice or music stuff

verbal cairn
cloud tundra
#

yeah ik

verbal cairn
verbal cairn
cloud tundra
verbal cairn
#

Mhm

manic wing
#

async def command(self, ctx)

#

you need a self because its a method of the class

blissful lagoon
#

please don't use ableist language

visual island
#

unwrap the CommandInvokeError

slate swan
#

having problems with cogs so i think im just going to import themyert

astral cobalt
#
It is strongly recommended to use Async PRAW: https://asyncpraw.readthedocs.io.
See https://praw.readthedocs.io/en/latest/getting_started/multiple_instances.html#discord-bots-and-asynchronous-environments for more info.
``` Im not sure what this means anyone have an idea?
slate swan
#

since your using praw which is sync with a async lib

astral cobalt
#

do I need to import asyncpraw instead of praw?

slate swan
#

pip install asyncpraw

import asyncpraw
astral cobalt
#

Sweet thank you, what about RuntimeWarning: Enable tracemalloc to get the object allocation traceback @slate swan

#
async def meme(ctx):
    subreddit = reddit.subreddit("memes")
    all_subs = []
    top = subreddit.top(limit = 50)
    for submission in top:
        all_subs.append(submission)
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    embed = discord.Embed(title = name, color=discord.Color.gold())
    embed.set_image(url = url)
    embed.set_footer(text=f"Asked by {ctx.author.name}")
    await ctx.send(embed=embed)```
visual island
#

you forgot to await something

astral cobalt
#

But theres already an await inside the meme function

pliant gulch
#

Since async praw is an async driver for praw, you now need to await the respective methods of praw

#

E.g subredit.top -> await subreddit.top

#

Maybe reddit.subreddit as well, I'm not sure I've never used praw

astral cobalt
#
                    client_secret='CLIENT_SECRET',
                    user_agent='CLIENT_AGENT') ``` so this needs an await?
visual island
#

no

pliant gulch
#

The class construction won't need an await unless their docs says so

#

Just await their methods

astral cobalt
#

Oh I see

ebon island
#

Can something like an HTTP error be wrapped in a try except loop?

astral cobalt
#

if I change subreddit = reddit.subreddit("memes") to subreddit = await reddit.subreddit("memes") then the bot doesent do anything

ebon island
#

is reddit.subreddit async?

astral cobalt
#
                    client_secret='CLIENT_SECRET',
                    user_agent='**')``` I believe
ebon island
#

that looks like an object constructor

astral cobalt
#

It doesent throw an error it just doesent do anything

ebon island
#

okay so, look at that above

#

you're defining an object of the type Reddit contained within asyncpraw package and accessing the "subreddit" method within it

#

look at the code from the package you imported and see if it is async

#

based on your description of the behavior I'd be willing to guess it isn't

astral cobalt
#

i imported asyncpraw. Thats the only thing I have imported and isnt that made to be async?

ebon island
#

You should inspect it to see if the method you are using is async

#

have you read the docs?

#

looks like it is

astral cobalt
#

@ebon island reddit = asyncpraw.Reddit( client_id="my client id", client_secret="my client secret", user_agent="my user agent", ) The docs say this is async and thats exactly what I have

#

Could it be that my user agent is wrong? or does that even matter?

slate swan
#

Whats happening???

ebon island
#

I'm not familiar with this package so I don't know the specifics of how it works, I'd suggest looking at what the subreddit method is actually doing

#

read the error Uni

slate swan
ebon island
#

why is it discord.py.self? is there a particular reason?

slate swan
#

old command but here @astral cobalt

@bot.command()
@commands.cooldown(1,120,commands.BucketType.user)
async def setup(ctx):
    print("setup command has been executed")
    subreddit = await reddit.subreddit("setups")
    all_subs = []

    top = subreddit.top(limit = 200)

    async for submission in top:
        if not submission.is_self:
            all_subs.append(submission)
    random_sub = random.choice(all_subs)

    name = random_sub.title
    url = random_sub.url
    
    em = disnake.Embed(title = name)
    if "jpg" not in url or "png" not in url:
        pass
    if "jpg" in url or "png" in url:
        em.set_image(url = url)
    await ctx.send(embed = em)
slate swan
ebon island
#

try having no version and just type the name of the package

#

so don't specify the version and see if that works

slate swan
#

ok

ebon island
#

if it doesn't you probably have a mistake in the package you are trying to access

#

link the github, I'll have a look just out of curiosity

astral cobalt
#

@slate swan Where does the useragent come from?

slate swan
astral cobalt
#

Oh okay lol

slate swan
ebon island
#

looks like a label

astral cobalt
#

Its still doing the same thing, the command works as in no errors are thrown but it doesent do anything in the discord

ebon island
#

does it say for it to do anything in the discord?

ebon island
#

I don't see it sending a message in the above snippet

pliant gulch
#

Shouldn't subreddit.top be awaited

astral cobalt
#

@ebon island ctx.send(embed = em ) is that sending it?

slate swan
pliant gulch
#

I'll take a look at the docs, I don't know much about asyncpraw

ebon island
#

yes, ctx not cts but yes, that would send an embedded message assuming you have defined what the embed params are

pliant gulch
slate swan
ebon island
#

in the above it is pulling embed definition from something called disnake and assigning the title to name which is defined by the random_sub.title above which is grabbed from a random.choice selection from all_subs which is a list constructed from submissions in subreddit.top with a limit of 200

ebon island
#

also should use list comprehension for that list in the above code

#

you can put the conditional on it

slate swan
#

its old but works so i wont bother

ebon island
#

fair, just something I noticed while trying to understand the code you'd posted

slate swan
#

yeah its like 6 months old

ebon island
#

where possible, list comprehensions should be used over appending a list manually

slate swan
#

🤷‍♂️

ebon island
#

whatever condition or case you apply to the append you can also apply to a comprehension and it will be faster

#

do you know how to do a list comprehension?

pliant gulch
#

List comp is the same speed, the syntax can be a bit over the top for simple things

#

At a point where you do so many things it's better to use a for-loop

slate swan
slate swan
#

ohh

slate swan
visual island
ebon island
#

comprehensions are faster and show a greater knowledge of the language

pliant gulch
pliant gulch
ebon island
#

yeah, they are icy

#

perhaps, but in the case above a list comprehension would have been clean and efficient for the purpose

ebon island
#

all_subs = [submission for submission in top if not submission.is_self]

should theoretically do the same thing and would likely be faster

slate swan
#

i see

ebon island
#

I haven't run the code but I expect it would work and create your list faster, it probably makes little difference from a human perspective since there are only 200 items max but just generally as engineers using language specific tricks like list comprehensions for optimization is good practice to get into since you will be more familiar with the syntax/implementation

slate swan
#

hmm i see

pliant gulch
# pliant gulch They are usually the same speed last I checked
In [1]: def for_loop() -> list[int]:
   ...:     ints = []
   ...:     for i in range(10):
   ...:         ints.append(i)
   ...:     return i
   ...: 

In [2]: def list_comp() -> list[int]:
   ...:     return [i for i in range(10)]
   ...: 

In [3]: %timeit for_loop
13.2 ns ± 1.03 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

In [4]: %timeit list_comp
13 ns ± 1.16 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
``` Yep, around the same speed
#

Although the first for list_comp is 1.16ns, whereas the for-loop is 1.03

slate swan
#

random question why isnt this responding to errors?

@bot.event
async def on_command_error(ctx,error):
    if isinstance(error, commands.CommandNotFound): 
        eror = "Unknown command"
    elif isinstance(error, commands.MissingRequiredArgument):
        eror = "Missing an argument"
    elif isinstance(error, commands.BadArgument):
        eror = "Not a valid argument"
    elif isinstance(error, commands.MissingPermissions):
        eror = "Missing permissions"
    elif isinstance(error, commands.MemberNotFound):
        eror = "Member not found"  
    elif isinstance(error, commands.UserNotFound):
        eror = "User not found"
    else:
        eror = f"Unknown error\n`\n{error}\n`"
        
    embed14 = disnake.Embed(title="Error!!!",
    description=eror,
    color=0xe74c3c,
    timestamp=datetime.datetime.utcnow()) 
    await ctx.send(embed=embed14)
astral cobalt
#

@slate swan Whats the iusername and password gonna be, just my default username an d reddit password? What if I log in with my gmail?

ebon island
#

when you put that in you should use .env variables

astral cobalt
#

Yeah i already did that, but should I use my email for username?

ebon island
#

good practice to get into, not having your passwords or other sensitive data in your code in case you push to git for example

slate swan
ebon island
#

haha yeah, best to get used to it now before it creates headaches in the future 🙂

astral cobalt
#

What about for password?

slate swan
#

idk i just reset the password to get my password

slate swan
slate swan
#

how come my username isnt my gmail's name then

#

what?

sage otter
#

I swear I feel like I just had a debate with panda about list comp vs everything else

pliant gulch
#

List comp is fine, imo its fine to use where it would fit, otherwise don't use it if it over complicates thing

astral cobalt
#

@slate swan I need a username and password but I used gmail for my reddit account so how would I get my username/password when I sign in w gmail

pliant gulch
#

the syntax acts sorta weird in the list comp rather than a straight forward for-loop

slate swan
#

example ^

astral cobalt
#

would my reddit password be my gmail password then?

#

since I use gmail to sign in to reddit

slate swan
#

dont think reddit can read your gmail password

astral cobalt
#

When. Igo to reddit to sign in instead of entering in a reddit password I clikc "sign in with gmail?"

#

So. Iwas asking what would my password be in that case

slate swan
#

YO

slate swan
#

how do I install the newer version

slate swan
slate swan
slate swan
#

?

visual island
pliant gulch
slate swan
slate swan
#

uh

visual island
slate swan
#

ok..

slate swan
#

your phone is gonna blow

#

LOL

visual island
#

nah it's pretty small

#

7 MB

slate swan
slate swan
pliant gulch
#

Not really an IDE

slate swan
#

so clean

visual island
# pliant gulch

ohh, i get the issue. Shouldn't you call the function in the timeit there? Your timeit there is just the time creating the function

visual island
slate swan
slate swan
visual island
#

hmm, did the error handler got dispatched?

visual island
#

and the error is still raised?

slate swan
pliant gulch
#

OH wait you are right, I should be calling it, sorry still a magic commands noob

#

I'll try again this time calling

#
In [2]: def for_loop() -> list[int]:
   ...:     ints = []
   ...:     for i in range(10):
   ...:         ints.append(i)
   ...:     return ints
   ...: 

In [3]: def list_comp() -> list[int]:
   ...:     return [i for i in range(10)]
   ...: 

In [4]: %timeit for_loop()
643 ns ± 151 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [5]: %timeit list_comp()
341 ns ± 5.24 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
#

Explains why earlier I thought they were about the same speed

#

Now I know kek, I wasn't calling it inside of the timeit

slate swan
#

ive never understood why

pliant gulch
#

Otherwise it wouldn't be defined

slate swan
pliant gulch
#

Plus, logically it just makes sense as well, compare [i for i in range(10)] compared to [for range(10)]

pliant gulch
slate swan
#

alr

pliant gulch
#

I don't read the Cpython source so I would have no idea how it works internally

#

I'm not the person to ask

slate swan
#

alr

slate moss
#

bruh

pliant gulch
slate swan
pliant gulch
#

Oh wait nevermind

#

Ignore what I said, lol

slate swan
#

alr lol

pliant gulch
#

I completely brain farted

slate moss
#
if message.content == ':acii-amogus':
      embed=discord.Embed(description="            ⣠⣤⣤⣤⣤⣤⣶⣦⣤⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀  \n⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⡿⠛⠉⠙⠛⠛⠛⠛⠻⢿⣿⣤⡀⠀⠀⠀⠀⠀  \n⠀⠀⠀⠀⠀⠀⠀⠀⣼⣿⠋⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⠈⢻⣿⣿⡄⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⣸⣿⡏⠀⠀⠀⣠⣶⣾⣿⣿⣿⠿⠿⠿⢿⣿⣿⣿⣄⠀⠀ \n ⠀⠀⠀⠀⠀⠀⣿⣿⠁⠀⠀⢰⣿⣿⣯⠁⠀⠀⠀⠀⠀⠀⠀⠈⠙⢿⣷⡄⠀\n⠀⠀⣀⣤⣴⣶⣶⣿⡟⠀⠀⠀⢸⣿⣿⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣷⠀\n⠀⢰⣿⡟⠋⠉⣹⣿⡇⠀⠀⠀⠘⣿⣿⣿⣿⣷⣦⣤⣤⣤⣶⣶⣶⣶⣿⣿⠀\n⠀⢸⣿⡇⠀⠀⣿⣿⡇⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠀\n⠀⣸⣿⡇⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠉⠻⠿⣿⣿⣿⣿⡿⠿⠿⠛⢻⣿⡇⠀⠀\n⠀⣿⣿⠁⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣧⠀⠀\n⠀⣿⣿⠀⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⠀⠀\n⠀⣿⣿⠀⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⠀⠀\n⠀⢿⣿⡆⠀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⡇⠀⠀\n⠀⠸⣿⣧⡀⠀⣿⣿⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣿⣿⠃⠀⠀\n⠀⠀⠛⢿⣿⣿⣿⣿⣇⠀⠀⠀⠀⠀⣰⣿⣿⣷⣶⣶⣶⣶⠶⠀⢠⣿⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⣿⣿⠀⠀⠀⠀⠀⣿⣿⡇⠀⣽⣿⡏⠁⠀⠀⢸⣿⡇⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⣿⣿⠀⠀⠀⠀⠀⣿⣿⡇⠀⢹⣿⡆⠀⠀⠀⣸⣿⠇⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⢿⣿⣦⣄⣀⣠⣴⣿⣿⠁⠀⠈⠻⣿⣿⣿⣿⡿⠏⠀⠀⠀⠀\n⠀⠀⠀⠀⠀⠀⠀⠈⠛⠻⠿⠿⠿⠿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀\n",color=0xff0000)
      await message.channel.send(embed=embed)
      await message.channel.send  ,
("**ඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞඞ**")```
slate swan
pliant gulch
#

Just to see if it actually dispatches

slate swan
#

already did lol

pliant gulch
#

on_command_error isn't dispatched?

slate swan
#

im having too many strokes rn

slate swan
pliant gulch
#

That probably means the event isn't being dispatched

slate swan
#

yes your correct

#

it isnt

pliant gulch
#

So you somehow aren't raising errors

slate swan
#

yep

pliant gulch
#

That would be why it isn't handling errors

slate moss
#

raid command is dumbpy if message.content == ':raid': while (1): await message.channel.send("THIS SERVER IS NOW RAIDED @everyone")

slate swan
#

im not that dumb lol

slate moss
#

bruh

#

dies

pliant gulch
slate moss
#
if message.content == ':help':
             
            embed=discord.Embed(description="**Prefix \":\"**\n\n**NO PREFIX COMMANDS**\n```sus = to send \"amogus\" message\namogus = to send \"sus\" message```\n**\":\" PREFIX COMMANDS**\n```:help = to show this embed message\n:acii-amogus = to show amogus image acii\n:spam = to show infinite spam \"SUS SUS SUS SUS AMOGUS SUS AMOGUS SUS SUS SUS SUSSYBAKA SUS SKIDDER SUS\" messages```\n**WARNING: THIS COMMAND IS NOT SAFE FOR\nOTHER SERVERS BECAUSE IT CAN RAID THE SERVER**\n||:raid||  `= to raid a server.`\n\n**ABOUT ME**\n```This bot is not actually done coded\nthis bot is been written in python by GetMbr#2137 and it need to goal 12 commands and messages. thank you```\n", color=0xFF9733) 
            
            await message.channel.send(embed=embed)```
slate swan
#

so i have this command

@client.command()
async def nick(ctx, nick):
    await ctx.author.edit(nick=nick)
    await ctx.send(f'Nickname was changed for {ctx.author.mention} ')

it only change the nickname without spaces, how can i change a nickname with spaces like "!nick nick testing" ?

slate moss
#

i like that bot that has no prefix

#

but its kinda useless

slate swan
#

@slate swan this should work ```py
@client.command()
async def nick(ctx,*, nick):
await ctx.author.edit(nick=nick)
await ctx.send(f'Nickname was changed for {ctx.author.mention} ')

#

aight thanks

pliant gulch
# slate swan nope

Make a new command, and inside of it call bot.dispatch("command_error", ctx, ValueError)

#

I just wanna see if the event is registered correctly

pliant gulch
#
@bot.command()
async def test(ctx) -> None:
    bot.dispatch("command_error", ctx, ValueError)
slate swan
#

oh mb

pliant gulch
#

No just call dispatch with those params

slate moss
#

ok

#

brb

pliant gulch
slate swan
#

alr

slate swan
#

gosh make it look a bit dumber

slate moss
#

this

slate swan
#

ok so you want me to call the func?

pliant gulch
#

Yes

slate moss
#

h

#

okk

slate swan
#

then why so complicated

#

lol

pliant gulch
#

Just do what I showed in the example

slate swan
pliant gulch
#

Nothing?

slate swan
#

doesnt print anything

pliant gulch
#

Ok, so you somehow didn't register the event correctly

slate swan
#

how so?

pliant gulch
#

Because dispatch("command_error", ...) should be calling the event callback registered to on_command_error

slate swan
#

i see

pliant gulch
#

And you say it isn't printing anything, so that must mean on_command_error isn't registered properly

slate swan
#

hm

pliant gulch
#

Maybe check your indents to see if your inside a function where you register the event? Not sure

#

It can be many things

raw latch
#

Do Discord bots required lot of ram?

pliant gulch
#

Then I'm not sure, all I know is that you just don't register it ¯_(ツ)_/¯

#

I'm sure you'll be able to find the issue after looking at your code for a bit

pliant gulch
slate swan
slate moss
slate swan
#

how do I pass in a user in my command

slate swan
#

yes in the function params

#

sorry

#

member: discord.Member

#

perfect, ty

raw latch
slate swan
slate moss
slate swan
raw latch
pliant gulch
slate swan
#

2gb is good too

pliant gulch
#

It's dependent on members because the bot has to cache all the members on startup

pliant gulch
#

that's what the main concern should be

slate swan
#

yep

worthy moat
#

Help:

#
@client.command(name='restart', alliases=['restart'])
async def Restart(ctx):
        if ctx.author.id not in teamid:
            await ctx.send(f'Bot zostanie zresetowany w przeciągu 5 sekund', delete_after=0.5)
            sleep(0.5)
            await ctx.send('Restartowanie...', delete_after=1)
            try:
                await client.logout()
            except EnvironmentError as e:
                print(e)
                client.clear()
            await ctx.send('Bot został zresetowany pomyślnie')





client.run(tokenbot)
slate swan
#

?

worthy moat
#

command don't work

slate swan
#

wdym it dont work

worthy moat
#

when i type =restart nothing happend on server and on pycharm console

#

btw in my country is 2:07AM

#

@slate swan pls hel

#

help*

slate swan
worthy moat
#

i use from time import sleep

slate swan
#

it will block your functions

#

use asyncio.sleep()

worthy moat
#

i don't use asyncio

#

but i can change it

slate swan
#

you do?

worthy moat
#

from time library to asyncio library

slate swan
#

no

#
import asyncio
worthy moat
#

no, change from time import sleep to import asyncio

slate swan
worthy moat
slate swan
#

what about it?

worthy moat
#

i just typed that

slate swan
#

and?

worthy moat
#

wait

slate swan
#

?

worthy moat
#

i used asyncio and changed from time.sleep(0.5) to asyncio.sleep(0.5)

slate swan
#

its a coro

#

and youll have to download asyncio

worthy moat
#

ok i downloaded it by pip install asyncio

slate swan
#

ok?

#

any error?

worthy moat
#

yes

#

but before im gonna type the code

#
@client.command(name='restart', alliases=['restart'])
async def Restart(self, ctx):
        if ctx.author.id not in teamid:
            await ctx.send(f'Bot zostanie zresetowany w przeciągu 5 sekund', delete_after=0.5)
            asyncio.sleep(0.5)
            await ctx.send('Restartowanie...', delete_after=1)
            try:
                await client.logout()
            except EnvironmentError as e:
                print(e)
                client.clear()
            await ctx.send('Bot został zresetowany pomyślnie')

Error

Ignoring exception in command restart:
Traceback (most recent call last):
  File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
    await self.prepare(ctx)
  File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
    await self._parse_arguments(ctx)
  File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
    transformed = await self.transform(ctx, param)
  File "C:\Users\Szymon\Desktop\MauBot\venv\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
#

Szymon is my username and MauBot is name of bot

slate swan
#

why do you have self?

worthy moat
#

idk

#

i just copied code from site

slate swan
#

do you have experience with classes?

worthy moat
#

no

teal oyster
#

what can make a bot show offline to some users when bot is acutally online? also bot cant send messages to that user
i have a alt account for testing but when bot wants to send message to my account it fails also my dm is open

slate swan
teal oyster
#

what feature

slate swan
#

the first question

teal oyster
#

i think its more like a general discord question

teal oyster
#

because when me and my friend blocked eachother for fun his staus showed offline

#

yes

#

but cant send messages

slate swan
teal oyster
#

show what

#

error?

slate swan
#

code bruh

#

or error

teal oyster
#

ok lemme try again

slate swan
#

How can I auto-publish a message which has been sent in an announcement channel?

teal oyster
#
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user

i dont think there is need for full error

#
            await member.send('Sorry but this server is currently closed! you can rejoin after server is opened again')
quaint epoch
slate swan
quaint epoch
#

my bot did the same thing

teal oyster
#

no i checked that

#

user is my alt account

quaint epoch
teal oyster
#

dm is open

slate swan
#

maybe the user doesnt accept dms from the guild

teal oyster
#

and didnt blocked the bot

quaint epoch
teal oyster
#

from guilds or a specific guild

slate swan
#

from the guild you want to dm someone from

teal oyster
#

if a specific guild i dont even know discord have that feature

#

oh

quaint epoch
teal oyster
#

i did

slate swan
teal oyster
#

just the member object or what

slate swan
#

print it out

teal oyster
#

wait

slate swan
#

if it prints itself it means it can only see itself and needs members intents

teal oyster
#

bruh

#

you could just say that

#

all intents are enabled

slate swan
#

alright

teal oyster
#

and i checked member is not itself

slate swan
#

can someone one help me setup and @slate swan setup up a site

teal oyster
teal oyster
#

now what

slate swan
#

sory

teal oyster
#

only information i know is bot status is offline for the alt

slate swan
teal oyster
#

wait i think i get it

slate swan
#

How can I auto-publish a message which has been sent in an announcement channel?

teal oyster
#

no it dont

#

so

#

bot kicks and then sends the message

#

does that change anything?

#

i dont think so

slate swan
teal oyster
#

i saw bots sending me messages without sharing a server with me

slate swan
#

if the member is not in the guild the bot cannot send a dm as it doesnt have any mutual guilds

teal oyster
#

but-

#

i see members and bots do that

#

without any mutual guilds

slate swan
#

are you trying to do a ban or kick command?

teal oyster
#

no

slate swan
#

what are you trying to do?

teal oyster
#

im trying to create a unique bot

#

hm

#

a thing to stop members from joining

slate swan
#

that does what exactly?

teal oyster
#

if server is closed by someone that have the permission no one can join

#

there was another way

#

ban the user and unban

slate swan
teal oyster
#

so what you think?

#

owner sits down and kick everysingle member by hand?

#

😂

teal oyster
#

im already using that

slate swan
#

and?

teal oyster
#

wdym and

slate swan
#

any error?

teal oyster
#

no i was chatting with you

#

lemme try

#

ah stupid cooldown

#

ok worked

slate swan
#

lol

teal oyster
#

but i have a question from you

#

if im not using on_member_join event

#

what else could i used?

#

i mean what you taught i was using

slate swan
#

idk lol

teal oyster
#

maybe you taught i wasnt even created that part idk

#

can you help a thing?

slate swan
teal oyster
#

spam join my server to see how much it takes to get rate limited lol

teal oyster
slate swan
slate swan
teal oyster
#

why?

#

no how much it take for my bot why should i need you if i wanted to get rate limited

slate swan
#

check docs

#

really not hard

teal oyster
#

i cant find it

#

anywhere that says the limits

#

i dont know a single thing about rate limits
just know there is a global limit and i think thats 50 but what about local limit

sick birch
#

Message rate limit from my experience is about 1 message per second

#

Changing channel names and probably some others has a rate limit of 2 per 10 minutes

pliant gulch
#

Its 5/5s

sick birch
#

Basically 1 per second

#

Sort of

pliant gulch
#

Not 1/1s

#

5/5s

sick birch
#

Yeah though I like to have the 1/1 rule of thumb

pliant gulch
#

But basically 1 per second

sick birch
#

Right

pliant gulch
#

Kek

sick birch
#

You could send 4 messages instantly

#

actually no

pliant gulch
#

You should be able to send 5 a second

sick birch
#

you could send 5 but the next one would take a bit longer

pliant gulch
#

Yes it would

sick birch
#

But it's best to try your best to stay under as I don't know what happens if you repeatedly go over the rate limit

pliant gulch
#

But discord.py's ratelimiter also uses locks per bucket

sick birch
#

Yeah that's good often times you don't have to worry about the rate limit too much

pliant gulch
#

Shameless flex, but I've implemented semaphores into my ratelimiter

#

😔

sick birch
#

I've heard of that, what exactly is it?

pliant gulch
#

But semaphore allows for multiple threads

#

Lock only allows one thread in

#

Meaning my ratelimit handler allows for concurrent requests

sick birch
#

Ah I see

#

I remember skimming it over lmao

#

Very cool stuff though

pliant gulch
#

There is an issue with start up with the ratelimiter although,

#

The gateway/bot endpoint has it's bucket depleted for some reason

#

Even though it's requested once

sick birch
#

I mean the servers won't care right if it's concurrent or not

pliant gulch
#

I have no clue what discord really thinks about it

#

I can't see their backend

sick birch
#

I don't think they differentiate

pliant gulch
#

Just don't fuck with the message delete stuff

#

The ratelimiter goes all wild with trying to do concurrent deletes

pliant gulch
small igloo
#

eh.. i need help, how to make my bot edit message when i add a reaction to the message, however, i already try to use the wait_for_reaction system, but idk how to implement it since it says that there is no attribute wait_for_reaction

pliant gulch
#

It isn't wait_for_reaction, its wait_for

#

!d discord.Client.wait_for

unkempt canyonBOT
#

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

Waits for a WebSocket event to be dispatched.

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

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

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

This function returns the **first event that meets the requirements**...
pliant gulch
#

You pass "reaction_add" to the event parameter of wait_for

#

This would then wait for a new reaction, then you can do what you want with that

stiff nexus
small igloo
pliant gulch
#

reaction_add is a string

#

Check would be a function which takes the same parameters as the event on_reaction_add

#

You would need to check if the message is the same message you want to delete

#

And wait_for is a method of your client, it's not magically defined

small igloo
pliant gulch
#

wait_for_reaction doesn't exist

small igloo
pliant gulch
#

Click on the docs link I sent, there should be an example on there

ebon island
#

How is error handling done with regards to DPy commands?

pliant gulch
ebon island
#

Where can I find more info on this? Leafing through the docs and not finding exactly that

pliant gulch
#

Your gonna need to read the source code

ebon island
#

What about documentation on how the end user handles errors/exceptions?

pliant gulch
#

Alright, guess it isn't gonna link

ebon island
#

Say for example I want a custom response to commandnotfound error?

pliant gulch
#

You get Context and Exception from the event

#

Just isinstance the error and check if it is CommandNotFound

#

If it is send a response via ctx

ebon island
#

Cool! Do they have examples on the docs of a couple errors being handled?

pliant gulch
#

Check the examples folder of the discord.py repository

#

They might have some examples there

frosty creek
#

the package

small igloo
#

how to check who give the reaction :3

slate swan
#

dm me if you really good at coding discord bots 🙂

frosty creek
ebon island
#

that info is in ctx salvare

small igloo
slate swan
slate swan
frosty creek
#

idk

slate swan
#

Pretty basic stuff

slate swan
#

and i need a dev dm for info lol

#

Just learn lol

#

Dpys git probably has commands for moderation

sullen shoal
#

you might want to have a look at rule 9

ebon island
#

The docs are a great resource and experimentation is good

slate swan
#

No lol

ocean leaf
#
Ignoring exception in on_message
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/commands/zlevelsys.py", line 34, in on_message
    collection.update_one({"_id": author_id}, {"$set": {"xp": new_xp}}, upsert = True)
UnboundLocalError: local variable 'new_xp' referenced before assignment
#

it is assigned abvoe

ocean leaf
#

it shd not be before the function?

slate swan
#

thats all you would need to make a discord bot

slate swan
slate swan
slate swan
#

but , this :/

ocean leaf
slate swan
#

yea

slate swan
slate swan
ocean leaf
slate swan
slate swan
#

Thats weird?

slate swan
slate swan
ocean leaf
slate swan
#

Lol

ocean leaf
slate swan
#

Lol

ocean leaf
#

thats what we are supposed to do as if i make the variable after using it, it wil throw error

slate swan
ocean leaf
#

add the variable after referrencing it?

slate swan
#

I dont really know seems good to me but all you gotta do is move it back

#

As it says its been reference before assignment

ocean leaf
#

so yeah

slate swan
#

Guess youll have to put it upfront

sullen shoal
ocean leaf
sullen shoal
#

so this stevendev guy ignored the example i gave in another server

slate swan
sullen shoal
#

on why it happens

sullen shoal
#

and a quick fix to it

sick birch
#

a vpn will solve your issue

sullen shoal
#

well the adult sites are also blocked in india and when I use it, it unlocks all the sites

sick birch
#

not advising you do so though

sullen shoal
#

however it cant change your ip

sick birch
sick birch
slate swan
ebon island
#

So I found

exception discord.ext.commands.CommandNotFound(message=None, *args)

in the docs, now I'm trying to work out how to implement it so it actually listens for that exception event, I'm presently trying via decorator as I am using cogs

sick birch
#

This is one of those errors where it's use full to catch it globally

#

so, you can use on_command_error()

ebon island
#

I saw some examples doing this, defining an async method by that name but when I tried it didn't work

sick birch
#

What do you mean "it doesn't work"

ebon island
#

it doesn't hit that code when it has the error, I tried printing and sending a message neither worked so it's not hitting it

slate swan
#
@bot.event
async def on_command_error(ctx,error):
    if isinstance(error, commands.CommandNotFound): 
        eror = "Unknown command"
    embed14 = disnake.Embed(title="Error!!!",
    description=eror,
    color=0xe74c3c,
    timestamp=datetime.datetime.utcnow()) 
    await ctx.send(embed=embed14) 

On mobile btw

ebon island
#
    async def on_command_error(self, ctx, error):
        if hasattr(ctx.command, 'on_error'):
            return

        error = getattr(error, 'original', error)
        if isinstance(error, discord.ext.commands.errors.CommandNotFound):
            await ctx.send('wow it worked')

for example

sick birch
#

on_command_error() is very high level so to speak, so it's more of a last resort for your code than anything. It'll try to find something else to propagate the error to, and if all else fails, it passes it to on_command_error() there's a chance that the error is being picked up by something else

sick birch
ebon island
#

was pulling from docs

sick birch
#

All you need to do is check the instance

ebon island
#

so you're saying just this will work?

    async def on_command_error(self, ctx, error):
        if isinstance(error, discord.ext.commands.errors.CommandNotFound):
            await ctx.send('wow it worked')
sick birch
#

also it's discord.ext.commands.CommandNotFound

sick birch
#

not discord.ext.commands.errors.CommandNotFound

ebon island
#

the discord.ext.commands.errors.CommandNotFound is the exact instance that it was showing in traceback

slate swan
#

I just add commands.CommandNotFound

slate swan
#

I was trying 3.10 and type hinting is so bad

pliant gulch
ebon island
#
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            await ctx.send('wow it worked')
pliant gulch
slate swan
#

You can send the error to witht he param

#
commands.Cog.listener()
async def on_command_error(self, ctx, error):
        if isinstance(error, commands.CommandNotFound):
            await ctx.send(f"the error: {error} has been raised") 
ebon island
#

not working with print above

#

so this can't be in a cog?

#

if it needs bot/client event?

slate swan
#

Dont really know i think so

pliant gulch
#

It does work in cogs

#

You just need to use commands.Cog.listener

upbeat otter
slate swan
#

And yes ik

upbeat otter
slate swan
ebon island
#

Works 🙂 Thank you!

upbeat otter
ebon island
#

Where can I find all of the names for errors like on_command_error? I'm looking at docs and not seeing exactly what I want

#

say like HTTP Error

ebon island
#

thank you 🙂

upbeat otter
ebon island
#

Hmm, doesn't appear to be there - I'm going to try and see if naming actually matters

slate swan
ebon island
#

Exception, I see in docs they have handled HTTPException so I'll have to find that so I can check if isinstance

slate swan
ebon island
#

I was looking at that page on docs a moment ago, I see a lot of other exceptions to handle but not just a straight HTTP exception, for example if a ctx.send command has issues reaching discord service I want it to handle that and retry sending the message

#

so I'd have to handle the HTTP exception and use that to send the request to retry presumably

upbeat otter
covert igloo
#

are you able to get messages from a channel and add them

#

i have it saving in a json file but its not getting the message from the channel

lament mesa
covert igloo
#

Yeah, i did that but im not getting any result

upbeat otter
covert igloo
#

ok hold on

ebon island
#

The issue is that we have a word generator algorithm, it stores the async task as an attribute in an object for the current word to be generated, and that spawns a new event and overwrites the old one barrel of monkeys style, the problem is if there is a 503 error it loses the chain and just stops and we need means to handle that error

#

like this:

server.task = asyncio.create_task(self.take_turn(server))

but the problem is that if the task does not send successfully it gives 503 and says task was never retrieved and doesn't continue at all

#

if I put a try except around that block would that be sufficient to catch it? I'm not sure because I don't know if the error is spawning in the scope of a try around that line for example

small igloo
#

how to make my bot can detect multiple reaction?

upbeat otter
#

maybe make a function or smth using client.wait_until_ready? I am not entirely sure tho

covert igloo
# upbeat otter code?
    async def on_message(self, message):
        msg = 'i' in message.content.lower()
        
        with open('cogs/data.json') as f:
                data = json.load(f)

        rev = int(data["rev-num"])
        rev += msg```