#discord-bots

1 messages · Page 479 of 1

hasty iron
#
roles = []

for role in Guild.roles:
  if role.name == your_name:
    roles.append(role)
stark bobcat
#

hlo i dunno why i am getting this error
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'bot' is not defined

#
@commands.command()
    async def latency(self, ctx):
      await ctx.send(bot.latency)```
using cogs
austere dagger
#

hello

#

can you suggest me some documents to learn async in python

boreal ravine
stark bobcat
boreal ravine
stark bobcat
slate swan
#

🤦‍♂️

stark bobcat
#

ok thanks i am new to cogs

boreal ravine
#

Make sure to multiply that otherwise

slate swan
#

and probably round it out your choice tho

stark bobcat
clever wind
#

omg your ign is just genious

dawn gale
#

hey goys how do i make calculator gui

#

my friend did this

#

it might be in my vsc code

hasty iron
#

you have to pass in that kwarg into the Bot constructor

slate swan
#

case_insensitive is for the bot class not command

dawn gale
#

my bot is case insensitive but idk how

boreal ravine
dawn gale
#

this is the code he sent me

boreal ravine
dawn gale
#

what that

boreal ravine
#

the one where u defined client

clever wind
#

guys what are the pros and cons of using a bot class or client class in discord py?

dawn gale
#

this is how i did it

hasty iron
#

stuff that allows you to make commands easily

boreal ravine
#

!d lower

unkempt canyonBOT
#

lower

Converts a string into all lowercase.

For example:

{{ value|lower }}
```  If `value` is `Totally LOVING this Album!`, the output will be `totally loving this album!`.
mortal thistle
#

Why I am facing this?

wanton cipher
wanton cipher
# mortal thistle yes

that is why, you need to have the actual discord module be the only thing called discord (try rename and see if it works)

wanton cipher
dapper cobalt
#

When a role gets deleted, does the len(role.members) become 0?

stiff nexus
#

how do i make the cmds not work in dms???

stark bobcat
#
@commands.Cog.listener()
    async def on_guild_join(self, guild):
        await guild.create_category("Mailer")```
why doesn't this work
slate swan
#

a error message?

stark bobcat
#

one min let me reinvite my bot then

#

nvm thanks fixed it

#

how do i get a channel id in a specific category?

crystal cliff
stark bobcat
#

no

#

it creates a catogoray when the bot joins a server

crystal cliff
stark bobcat
#

!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/stable/api.html#discord.Member "discord.Member") leaves or joins a [`Guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
boreal ravine
stark bobcat
hasty iron
#

what if the bot doesn’t have permissions

stark bobcat
#

smthing like modmail

crystal cliff
hasty iron
#

also that’s a bad idea

stark bobcat
#

ye

stark bobcat
crystal cliff
hasty iron
#

you should make it into a command instead

stark bobcat
#

hmm

#

why

crystal cliff
stark bobcat
#

when it's event it's automated

crystal cliff
slate swan
#

!d discord.Guild.create_category

unkempt canyonBOT
#

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

Same as [`create_text_channel()`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") except makes a [`CategoryChannel`](https://discordpy.readthedocs.io/en/stable/api.html#discord.CategoryChannel "discord.CategoryChannel") instead.

Note

The `category` parameter is not supported in this function since categories cannot have categories.
patent lark
patent ivy
#

hi quick question

#
@client.command()
@commands.has_permissions(manage_messages=True)
async def manage(ctx):
    await ctx.send("YOWZA")``` so this only send if I have manage_messages
#

how do I make it send a seperate message if you dont have that perm?

unkempt canyonBOT
#

discord.on_command_error(ctx, error)```
An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

A default one is provided ([`Bot.on_command_error()`](https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.on_command_error "discord.ext.commands.Bot.on_command_error")).
slate swan
#

use this event

patent ivy
#

where do I put it

slate swan
# patent ivy where do I put it

example:

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, MissingPermissions):
        await ctx.send(error)
patent ivy
#

ah thanks

#

so that can go anywhere in the code

#

and if that event happens that code will trigger?

slate swan
#

yea is your error handler

patent ivy
#

I am very new to this type of program

#

thanks

slate swan
#

An error handler that is called when an error is raised inside a command either through user input error, check failure, or an error in your own code.

patent ivy
#

the missingpermissions in undefined

#

@slate swan

wicked atlas
patent ivy
#

oh discord.missingpermissions

#

that don't work either

stark bobcat
wicked atlas
#

Have you spelled it in all lowercase like you are sending here?

patent ivy
#

no

slate swan
wicked atlas
#

Ah yes, thats a commands error

patent ivy
#

thx

#

it work now

#

so what exactly is ctx

#

I am not really sure

dim wing
#
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, reaction, user):

It says user argument is missing because it should have 2 arguments but it is in a cog so....

wicked atlas
#

!d discord.ext.commands.Context

unkempt canyonBOT
#

class discord.ext.commands.Context(**attrs)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
patent ivy
#

so when I do something like ctx.send

wicked atlas
patent ivy
#

what does that mean

wicked atlas
#

!d discord.on_raw_reaction_add

unkempt canyonBOT
#

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

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

The Context object gives you the "context" in which a command happened

dim wing
patent ivy
#

alright next thing

#

how do I get a function that runs everytime a message is sent

#

and get that message

dim wing
#

Im defining my functions like this in my class:

    @staticmethod
    async def get_money(user_id):

and call them with :

await Cog.get_money(ctx.author.id)

I was wondering if i should defining my function without @staticmethod (and without async?)

dim wing
#

!d discord.on_message

unkempt canyonBOT
#

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

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/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/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
slate swan
#

Hey, can we reset the cooldown of a specific command?

#

Like I dunno how pQuack

slate swan
#

@commands.cooldown(trigger,seconds,type)

#

How do I reset it?

dim wing
#

!d discord.ext.commands.Command.reset_cooldown

unkempt canyonBOT
dim wing
#

this?

slate swan
#

how can i make a command not show in the help menu ?

boreal ravine
#

is there a module for activity? I mean like the rich presence thingy cause I wanna make my own rich presence if I can. Like this ^^

boreal ravine
slate swan
#

thanks

slate swan
#

Ill try

slate swan
slate swan
#

You can modify the help command itself, I forgot how tho

slate swan
boreal ravine
slate swan
#

Uhm no, you dont have to disable it

#

Theres a kwarg in Bot() called help_command and as argument, you can give DefaultHelpCommand()

inland venture
#

how do i make it so that I could make my bot work on all channels

patent ivy
#

ok hard one

#

I need to get the names of everyone in a call

#

the call being grabbed from whatever one the message sender is in

#

is it possible?

slate swan
brisk helm
#
@perms_enable_check(ban_members=True)




  def perms_enable_check(permisions):
    async def enable_rola_check(ctx):
        db = sqlite3.connect("perms.db")
        curosor = db.cursor()
        curosor.execute("SELECT * FROM perms WHERE guild_id = ? AND command = ?",(ctx.guild.id,ctx.command.name,))
        wynik = curosor.fetchall()
        if not wynik:
            if ctx.message.author.guild_permissions.permisions:
                return True
            await False_enable_check(ctx)
            return False
        else:
            curosor.execute("SELECT * FROM perms WHERE guild_id = ? AND command = ?",(ctx.guild.id,ctx.command.name,))
            data = curosor.fetchall()

                
            if not data:
                if ctx.message.author.guild_permissions.permisions:
                    return True
                await False_enable_check(ctx)
                return False #
only part of the comedy``` Why this return me error
brazen seal
#

I can do in python the bot has count people in my server and refreshing this in 5 minutes?

brisk helm
unkempt canyonBOT
#
Not in a million years.

No documentation found for the requested symbol.

slate swan
#

Uhhh

slate swan
#

The exception

brazen seal
boreal ravine
#

How am I supposed to change my bot's status in the bot constructor if client isn't defined yet because it's on the same line? Like for example, py client = commands.Bot(command_prefix=commands.when_mentioned_or('.'), case_insensitive=True, intents=intents, activity=discord.Activity(type=discord.ActivityType.listening, name=f"{len(client.guilds)} guild(s)")) Error: ```py
[pyflakes] Undefined name 'client'

slate swan
#

Nvm

boreal ravine
brazen seal
#

Yes i know i do this and bot set status only one time and i don't know why his not refreshing :/

slate swan
brisk helm
# slate swan Whats the error output???

raise errors.ExtensionFailed(key, e) from e discord.ext.commands.errors.ExtensionFailed: Extension 'for_fun.giv' raised an error: TypeError: perms_enable_check() got an unexpected keyword argument 'ban_members'

slate swan
#

Just do it in on_ready

crystal cliff
wicked atlas
river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

inland venture
inland venture
brazen seal
pliant gulch
visual island
boreal ravine
slate swan
river walrus
#

And gotten better

slate swan
slate swan
#

I cannot find what perms_enable_check() does

brisk helm
slate swan
brisk helm
brisk helm
# slate swan @commands.has_permissions(ban_members=True)
def perms_enable_check(permisions):
    async def enable_rola_check(ctx):
        db = sqlite3.connect("perms.db")
        curosor = db.cursor()
        curosor.execute("SELECT * FROM perms WHERE guild_id = ? AND command = ?",(ctx.guild.id,ctx.command.name,))
        wynik = curosor.fetchall()
        if not wynik:
            if ctx.message.author.guild_permissions.permisions:
                return True
            await False_enable_check(ctx)
            return False
        else:
            curosor.execute("SELECT * FROM perms WHERE guild_id = ? AND command = ?",(ctx.guild.id,ctx.command.name,))
            data = curosor.fetchall()

                
            if not data:
                if ctx.message.author.guild_permissions.permisions:
                    return True
                await False_enable_check(ctx)
                return False
            if ctx.message.author.guild_permissions.administrator:
                return True
            for i in data:
                role = ctx.guild.get_role(int(i[3]))
            for typ in data:
                if typ[2] == "allow":
                    if role in ctx.author.roles:
                        return True
                    await False_enable_check(ctx)
                    return False
                if typ[2] == "deny":
                    if role in ctx.author.roles:
                        await False_enable_check(ctx)
                        return False
                    return True



    return commands.check(enable_rola_check)```
inland venture
slate swan
inland venture
#

i ended with error

slate swan
#

Huh

brisk helm
inland venture
wicked atlas
unkempt canyonBOT
#

Assignment vs. Comparison

The assignment operator (=) is used to assign variables.

x = 5
print(x)  # Prints 5

The equality operator (==) is used to compare values.

if x == 5:
    print("The value of x is 5")
slate swan
slate swan
slate swan
inland venture
#

k

#

ty!

slate swan
#

That came from typing too fast

#

Lol

inland venture
#

also how do i define ctx

brisk helm
inland venture
#

im a noob 😢

slate swan
#

In a command

slate swan
#

Ah you got message

#

@inland venture replace ctx with message

#

message.guild.channels

slate swan
#

lol

inland venture
#

k ty!

slate swan
brisk helm
slate swan
#

Plus I dont know what the code supposed to do

patent ivy
brisk helm
#

if ctx.message.author.guild_permissions.permisions: AttributeError: 'Permissions' object has no attribute 'permisions'

brisk helm
#

what i can do?

hasty iron
#

you want to check the passed in permissions?

#

if so use getattr

#

!d getattr

unkempt canyonBOT
#

getattr(object, name[, default])```
Return the value of the named attribute of *object*. *name* must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, `getattr(x, 'foobar')` is equivalent to `x.foobar`. If the named attribute does not exist, *default* is returned if provided, otherwise [`AttributeError`](https://docs.python.org/3.10/library/exceptions.html#AttributeError "AttributeError") is raised.

Note

Since [private name mangling](https://docs.python.org/3.10/reference/expressions.html#private-name-mangling) happens at compilation time, one must manually mangle a private attribute’s (attributes with two leading underscores) name in order to retrieve it with [`getattr()`](https://docs.python.org/3.10/library/functions.html#getattr "getattr").
slate swan
#

i have this code. It works but it answers like this "(24, '/', '64')" when i want it to look like this "24/64". Any ideas?

#
r = requests.get('http://51.77.136.2:30120/dynamic.json')


events = r.json()


@client.command()
async def status(ctx):
  em = discord.Embed(title='Apollo Project', description=(events['clients'],'/',events['sv_maxclients']), color=orange)
  await ctx.send(embed=em)
wicked atlas
#

!strings

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

stiff nexus
#
    @tasks.loop(minutes=10)
    async def task(self):
      c = self.bot.get_channel(878678693520744468)

      list = llists.list
      subreddit = random.choice(list) 
      
      async with aiohttp.request("GET", url = subreddit) as resp:
        json = await resp.json()
      while True:
        data = json['data']
        if not data['children']:
          pass
        else:
          break
        
      data = random.choice(data['children'])['data']
      sub = data['subreddit_name_prefixed']
      sub_N = data['subreddit']
      title = data['title']
      url = data['permalink']
      image_url = data['url']

      ems= discord.Embed(title=f"{title[:256]}", url=f"https://reddit.com{url}" , color=discord.Colour.random())
      ems.set_image(url=image_url)
      await c.send(embed=ems)
``` not sending anything. not getting any errors
boreal ravine
vale narwhal
#

Can i make the args use string that i declared?
Like

@bot.command()
async def test(ctx, *, args):
   hello = 10
   lel = 20
   total = 90 + args 
   await ctx.send(total)

basically use the hello if args was hello and use lel if args was lel

P.S I don't want to use if because the code that im using is kinda long and I don't want to make if args == BLAHBLAH for all of it...

wicked atlas
wicked atlas
#

Beacuse data["children"] might come out as falsey

#

What value is stored in there?

hasty iron
wicked atlas
boreal ravine
#

okay

hasty iron
#

that was a bug

#

you have to update your python version

slate swan
#

3.9.7

boreal ravine
#

okay

wicked atlas
slate swan
#

mhm

vale narwhal
river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

wicked atlas
#

!rule 6 technically

unkempt canyonBOT
#

6. Do not post unapproved advertising.

river walrus
#

You may ask them

river walrus
boreal ravine
vale narwhal
boreal ravine
vale narwhal
boreal ravine
river walrus
boreal ravine
#

lol

vale narwhal
boreal ravine
#

ok

vale narwhal
#

ok

vale narwhal
maiden fable
vale narwhal
maiden fable
#

Calm down with the emoji, @vale narwhal

maiden fable
river walrus
maiden fable
vale narwhal
#

Wasn't it optional

maiden fable
#

Yea

#

By default it is online only

vale narwhal
maiden fable
river walrus
wicked atlas
vale narwhal
maiden fable
#

Also imagine making an empty API call

boreal ravine
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

maiden fable
#

And sending two API calls in 10 seconds

vale narwhal
#

Just straight use it in bot.event

maiden fable
#

You are inviting ratelimits

vale narwhal
#

if you didn't set the multiple status

river walrus
vale narwhal
river walrus
vale narwhal
#

lmao

slate nymph
#

i want to make a bot command which will accept 2 arguments and will return one of them randomly... How do i make one

river walrus
# vale narwhal lmao

jokes aside, since you work with djs, will you be lending a hand with the project?

upbeat otter
#

Guys, this gives me an error: cant extract video

class YTDLSource(discord.PCMVolumeTransformer):
    YTDL_OPTIONS = {
        'format': 'bestaudio/best',
        'extractaudio': True,
        'audioformat': 'mp3',
        'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
        'restrictfilenames': True,
        'noplaylist': True,
        'nocheckcertificate': True,
        'ignoreerrors': False,
        'logtostderr': False,
        'quiet': True,
        'no_warnings': True,
        'default_search': 'auto',
        'source_address': '0.0.0.0',
    }
@commands.command(name='play')
    async def _play(self, ctx: commands.Context, *, search): 
        if not ctx.voice_state.voice:
            await ctx.invoke(self._join)

        async with ctx.typing():
            try:
                source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
            except YTDLError as e:
                await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
            else:
                song = Song(source)

                await ctx.voice_state.songs.put(song)
                await ctx.send('Enqueued {}'.format(str(source)))

vale narwhal
river walrus
maiden fable
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)
upbeat otter
#

thenx

#

for telling

vale narwhal
pliant gulch
maiden fable
river walrus
maiden fable
#

Yea one is that

pliant gulch
#

Ok, I thought they were talking about change presence

slate nymph
pliant gulch
#

As that has no ratelimit since its on the websocket

maiden fable
pliant gulch
#

Rather there is a queue I think or some other type deal

maiden fable
slate nymph
#

context is args 1 right?

maiden fable
#

Yea

#

Wait no

pliant gulch
#

Its done on the websocket

maiden fable
#

Ah, didn't know that. Thanks for telling!

pliant gulch
#

You still don't want to be spamming it

maiden fable
#

Yea

vale narwhal
#

He didn't even change multiple presence yert

#

Why don't he put that straight into bot.event

#

coughs

maiden fable
vale narwhal
#

done

#

Your wish

maiden fable
#

Haha

slate nymph
#

async def choose(ctx,*args):
await ctx.channel.send(random.choice(args))

slate swan
#

How to get the Command object of a given command?

slate nymph
#

says choose isnt defined

vale narwhal
slate nymph
#

i did

maiden fable
#

they mean choose bro...

hasty iron
vale narwhal
slate swan
vale narwhal
#

oh yes

slate nymph
#

sure

maiden fable
vale narwhal
#

lmao

slate swan
# maiden fable Wym

Like I wanna reset the cooldown for a command, but therefor I need the object itself [ Command.reset_cooldown(ctx) ]

slate nymph
hasty iron
#

you can use Bot.get_command

slate swan
#

Or how does that woooorkerk

hasty iron
#

and there is Context.command

slate swan
final iron
lament mesa
maiden fable
#

🤣 I love it when uvloop isn't available for windows and pip just tries to install it again but errors out

slate nymph
#

okay thanks

slate swan
#

Ah I see

hasty iron
slate swan
#

Well I got the Context so that should be enoughhh

maiden fable
vale narwhal
maiden fable
#

But yea, that is a life saver

pliant gulch
#

Just use linux on your main machine

pliant gulch
#

I'm joking

vale narwhal
pliant gulch
#

But srs should check it out, fresh air from windows garbage

maiden fable
#

But yea, Windows 10 has many bugs and garbage, agreed

pliant gulch
#

Bugs I could care less for, its the privacy

bitter depot
#

Let's keep this channel on-topic please guys

maiden fable
#

haha

bitter depot
#

!ot for general discussion

unkempt canyonBOT
maiden fable
#

Sorry Tizzy

slate nymph
#

what is ctx?

#

!ctx

maiden fable
unkempt canyonBOT
#

class discord.ext.commands.Context(**attrs)```
Represents the context in which a command is being invoked under.

This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.

This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/stable/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
maiden fable
#

BTW, anyone here knows how to use asyncio to make my discord bot install a module (uvloop) automatically if it is hosted on linux?

pliant gulch
#

Are you using poetry?

maiden fable
#

I have to use asyncio.create_subprocess_shell?

#

nah

pliant gulch
#

No venv for your bot??

slate nymph
#

any doc for args?

maiden fable
#

What do u expect

maiden fable
pliant gulch
#

Are you getting your bot ready for a VPS or something?

maiden fable
#

The VPS is linux, so uvloop is gonna work there

pliant gulch
#

Ok, take a look at poetry really recommend, so you can install reqs easy

maiden fable
#

Ah ok

pliant gulch
#

Also you can set uvloop in there to only install when its on linux

#

I'll send my pyproject.toml in my own bot's repo

maiden fable
#

Thanks!

pliant gulch
#

Notice the markers

slate swan
#

can someone help me with this

#

cause im kinda dumb dumb

maiden fable
#

Thanks 😄

slate swan
#

info = await self.bot.loop.run_in_executor (None, lamda, youtube_dl.YoutubeDL({'format':'best audio', 'quiet' : True})
= extract_info(f"ytsearch{amount} : {song}", download=False, ie_key="YoutubeSearch"))
whats broken here?

bitter depot
#

I'm afraid we can't help with YTDL here as it violates YouTube's ToS and thus our #rules #5 @slate swan

pliant gulch
slate swan
#

ok

slate nymph
#

how do i design my help command?

maiden fable
pliant gulch
#

Ok, just asking because uvloop breaks any subclassed help command

maiden fable
#

Oh?

pliant gulch
#

Which cython does not like

#

Which is what uvloop uses

maiden fable
#

Ah

patent lark
#

👍

maiden fable
#

Also, have you ever tried converting the bot to Cython?

unkempt canyonBOT
#

src/exts/help.py lines 20 to 28

def __new__(
    cls: t.Type[CustomHelpCommand], *args, **kwargs
) -> CustomHelpCommand:  # Here to appease uvloop
    return super().__new__(cls)

def copy(self):  # Here to appease uvloop
    obj = self.__class__(self.bot)
    obj._command_impl = self._command_impl
    return obj```
maiden fable
#

Ah ok thanks

slate nymph
#

This help command looks jerk how do i modify it?

pliant gulch
#

You can take my help command :^)

#

Or look at a guide for subclassing the help command

maiden fable
unkempt canyonBOT
#

class discord.ext.commands.HelpCommand(**options)```
The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).

This means that relying on the state of this class to be the same between command invocations would not work as expected.
pliant gulch
#

!customhelp

unkempt canyonBOT
#

Custom help commands in discord.py

To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000

maiden fable
#

I always forget that tag

slate nymph
maiden fable
#

Me whose help command is divided between 3-4 files: :stare:

pliant gulch
#

Probably because you didn't subclass

#

Way more compact to subclass since its all done for you already anyhow

slate nymph
maiden fable
#

Well, yea. But personally, I find using the deco easier

pliant gulch
slate nymph
#

bruh?

pliant gulch
#

Its only 127 lines long

maiden fable
#

I don't know... Lemme see

slate nymph
#

wow

pliant gulch
#

Not counting the hyperview stuff*

#

Since its a util, and not strictly used on the help command only

lament mesa
pliant gulch
#

If I did it would still be under 300 lines

maiden fable
#

115 lines in one file only

#

there are 3 files

#

150 for me (approx)

patent lark
#

bruh.

maiden fable
#

hehe

patent lark
#

mines only 98

maiden fable
#

What about @unkempt canyon :stare:

lament mesa
pliant gulch
#

Button paginators are pretty simple to make

patent lark
pliant gulch
#

I could've made mine more compacted

lament mesa
pliant gulch
#

Why would you handle formatting in a paginator?

lament mesa
#

splitting the list into pages

pliant gulch
#

My paginator strictly paginates all the embed generation is done outside of it

maiden fable
#

I forgot what I was gonna do :stare:

pliant gulch
#

Hence again, util not strictly used for one thing

pliant gulch
pliant gulch
#

Oh, I was talking about discord buttons

lament mesa
#

too lazy to rewrite the paginator to use buttons

maiden fable
#

Well buttons are slower than reactions, soooo 🤷‍♂️

pliant gulch
lament mesa
pliant gulch
inland venture
#

if message.channel.name == 'nice-place':
if user_message.lower() == 'hello':
await message.channel.send(f'Hello {username}!')
return

maiden fable
#

Yea that is true tho

inland venture
#

what do i type to make my bot do it on all channels

patent lark
maiden fable
#

andy also using jsk?

#

w o w

pliant gulch
#

I have no idea if the cached property even works to save time

maiden fable
#

Thought you made your own eval

#

:stare:

pliant gulch
#

I'm just hoping I won't need to keep calling get_command

maiden fable
#

Hmm

#

time to find other bots

pliant gulch
#

I would say in this repo, the thing that took me the most time was the warn sql code

maiden fable
#

Eh? Lemme see

lament mesa
#

Use pg_orm

maiden fable
#

Wait, what does DO $$ do?

pliant gulch
#

no clue I'm sql noob

maiden fable
#

You only wrote that code

maiden fable
#

Clean 😄

pliant gulch
#

Well do $$ is basically just the function

maiden fable
#

Ah ok

pliant gulch
#

with my limited sql knowledge

maiden fable
#

Ah ok

#

I really want match case 🥺

lament mesa
#

dont we all

maiden fable
#

idk xD

pliant gulch
#

Just make a mapping at this point

maiden fable
#

?

pliant gulch
#

I actively avoid many if statements like that

maiden fable
#

h o w

pliant gulch
#

So I just make a mapping

maiden fable
#

Any example?

#

sends repo link again

pliant gulch
#
OPTION_MAPPING: typing.Dict[str, typing.Callable] = {"opt1": func1, "opt2": func2}

if user_choice in OPTION_MAPPING:
....return OPTION_MAPPING[user_choice](...)
maiden fable
#

Ah

#

Hmm, thanks for that! I'mma try that

#

So I can also make a single function/method and just use args and kwargs in it, no?

pliant gulch
#

Yes you could

maiden fable
#

And pass it to mapping

#

Cool

#

Thanks a ton

#

BTW u using typing.Dict... Is it different from dict?

hasty iron
#

no

#

i mean yes

#

in <3.10 doing something like dict[str, Any] would result in an error

maiden fable
#

Oh

#

but not with typing.Dict, ight?

hasty iron
#

yes

pliant gulch
#

3.10 allows for dict[..., ...]?

#

Pog

hasty iron
#

yes

pliant gulch
#

Well, actually

maiden fable
#

and I used to think I wrote the wrong syntax

pliant gulch
#

In <3.10 you could import annotations from __future__

#

And use dict[..., ...]

#

As it turns all annotations into strings

hasty iron
#

right but dict[…, …] looks ugly

pliant gulch
#

Yea, prefer typing.Dict[..., ...]

slate nymph
#

like from where

#

also do i need to remove help command for that?

slate swan
#
@bot.command()
async def login(ctx):
    embed1 = discord.Embed(description='Please pay `50 Zains` to the authority.', color=0xa2f29b)
    await ctx.send('got you, have fun! to logout write `!logout`.')
    with open('logged.json', 'w') as logged:
        json.dump(ctx.author.id, logged)
    await asyncio.sleep(5 * 60)
    with open('logged.json', 'w') as logged:
        if ctx.author.id in logged:
            await ctx.send(content = f'||{ctx.author.mention}||', embed = embed1)
    while True:
        await asyncio.sleep(10800)
        with open('logged.json', 'w') as logged:
            if ctx.author.id in logged:
                await ctx.send(content=f'||{ctx.author.mention}||', embed=embed1)

at the

        if ctx.author.id in logged:

line it says that the filr is not readable, what's wrong?

pliant gulch
# slate nymph how should i import it?

Its, not a package you import rather just take a look at the code as a reference, you don't need to remove the help command as it overwrites bot.help_command when the cog is loaded.

#

You also would need to checkout the code for hyperview which the help command uses as a paginator

maiden fable
#

BTW andy have u tried converting a discord bot to Cython before?

pliant gulch
#

No I havent

#

I don't see the point of doing so either way

hasty iron
#

why would you want to anyways

maiden fable
#

Just asking

#

Yay the mapping works 😄

slate nymph
#

it says ..utills and..core cannot be resolved

pliant gulch
#

Use it as a reference

#

It won't work directly copy and pasted

maiden fable
#

lol

slate nymph
#

lol

pliant gulch
maiden fable
#

So it is responding twice

#

and returning an already responded error

#

I will fix it in some time lol

slate nymph
#

import discord from discord.ext.commands.core import Command #lemontree bot import bot_token import random from discord.ext import commands bot = commands.Bot(command_prefix="$") @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) activity = discord.Game(name="prefix is $") await bot.change_presence(status=discord.Status.online, activity=activity) @bot.command() async def echo(ctx,*args): response = "" for arg in args: response = response + " " + arg await ctx.channel.send(response) @bot.command() async def hello(ctx): rnd_messages = ['Hi hope you are having a wonderful day', 'Hello', 'Hi' ] await ctx.channel.send(random.choice(rnd_messages)) @bot.command(name='spam', help='Spams the input message for x number of times') @commands.is_owner() async def spam(ctx, amount:int, *, message): for i in range(amount): await ctx.send(message) @bot.command() async def choose(ctx,*args): await ctx.channel.send(random.choice(args)) bot.run(bot_token.token)
Heres my code

spring flax
unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate nymph
#

wut

stiff nexus
#
    @tasks.loop(minutes=10)
    async def task(self):
      c = self.bot.get_channel(878678693520744468)

      list = llists.list
      subreddit = random.choice(list) 
      
      async with aiohttp.request("GET", url = subreddit) as resp:
        json = await resp.json()
      while True:
        data = json['data']
        if not data['children']:
          pass
        else:
          break
        
      data = random.choice(data['children'])['data']
      sub = data['subreddit_name_prefixed']
      sub_N = data['subreddit']
      title = data['title']
      url = data['permalink']
      image_url = data['url']

      ems= discord.Embed(title=f"{title[:256]}", url=f"https://reddit.com{url}" , color=discord.Colour.random())
      ems.set_image(url=image_url)
      await c.send(embed=ems)
```help??? not sending anything. not getting any errors
slate nymph
#
from discord.ext.commands.core import Command #lemontree bot
import bot_token
import random
from discord.ext import commands
bot = commands.Bot(command_prefix="$")
@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))
    activity = discord.Game(name="prefix is $")
    await bot.change_presence(status=discord.Status.online, activity=activity)
@bot.command()
async def echo(ctx,*args):
    response = ""
    for arg in args:
        response = response + " " + arg
    await ctx.channel.send(response)
@bot.command()
async def hello(ctx):
    rnd_messages =  ['Hi hope you are having a wonderful day', 'Hello', 'Hi' ]
    await ctx.channel.send(random.choice(rnd_messages))
@bot.command(name='spam', help='Spams the input message for x number of times')
@commands.is_owner()
async def spam(ctx, amount:int, *, message):
    for i in range(amount): 
        await ctx.send(message)
@bot.command()
async def choose(ctx,*args):
    await ctx.channel.send(random.choice(args))
bot.run(bot_token.token) ```
#

heres my code then

celest pewter
#

Has anyone posted a queue music bot discord?

maiden fable
#

@patent lark

patent lark
#

hmm

maiden fable
#

Hey @pliant gulch (sorry for the ping), but mind helping me?

pliant gulch
#

Problem tells me whatever option is, that it isn't in the mapping

#

Print out option I guess

maiden fable
#

Hmm ok

#

nothing was printed

#

Breh

pliant gulch
#

Would mean option is None then

maiden fable
#

And how did u know option is not in the mapping, that is why its sending twice?

pliant gulch
#

No, I knew because it wasn't printing 1

maiden fable
#

ah

#

so now what

pliant gulch
#

Seems like this is prob a user input error?

maiden fable
#

I mean, it is trying to send that same option twice, which I selected

hasty iron
#

actually why are you even executing those functions inside the mapping?

pliant gulch
#

Seems like this should work fine, if inputted correctly

hasty iron
#

instead you could just remove await

maiden fable
#

eh, then how can I do?

hasty iron
#

grab the item from the mapping and then await it

maiden fable
#

ah ok

pliant gulch
#

Otherwise you would be calling a lot of unneeded stuff

#

Would be super inefficient

maiden fable
#

Hmm ok lemme try now

#

not it totally failed

#

like, it is trying to execute only one single method (the commands one)

hasty iron
#

isnt that what you want

maiden fable
#

It is executing that even when I select another option

hasty iron
#

what is your current code

maiden fable
hasty iron
#

so, no matter what you input it always executes 'commands'

maiden fable
#

Yea

pliant gulch
#

What does option print out?

#

How do you input it?

maiden fable
#

Nothing

#

not even a new line

pliant gulch
#

If option is None it should not be passing the if statement

maiden fable
pliant gulch
#

None the less, calling commands

maiden fable
#

but then, how is the function getting called?

#

wait

#

Lemme see if I overwrote something

#

nope, I don't think so

dusky ocean
#

how do i change the role icon of a role using a discord bot?

slate swan
#

does anyone have autorole code I can barrow?

#
@bot.event
async def on_member_join(member):
    role = discord.utils.get(member.server.roles, id="Id Here")
    await bot.add_roles(member, role)```
#

this is mine

#

but it doesnt work

bitter depot
pliant gulch
maiden fable
#

Thanks!

slate swan
#

any autrole code I can use?

hasty iron
#

no

slate swan
#

This is my code: #AutoRole Note: Not Included @bot.event async def on_member_join(member): role = discord.utils.get(member.server.roles, id="888819465020649533") await bot.add_roles(member, role)

#

it doesnt work

bitter depot
#

That's really old code

slate swan
#

but no errors were given

hasty iron
#

!d discord.Member.add_roles

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/stable/api.html#discord.Role "discord.Role")s.

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

ahhh

#

so its just out of date

hasty iron
#

and its Member.guild

bitter depot
#

bot.add_roles(member, role) --> member.add_roles(role)
member.server --> member.guild
ids are now integers not strings
@slate swan

slate swan
#

ok thanks

hasty iron
#

not Member.server

solid summit
#

Is the discordpy v2 beta worth using or should I seek a fork or maybe a diff lib?

brazen raft
#

Wrong reply, meant to reply @solid summit

solid summit
#

I'll take a look at it

past ermine
#

I have a question:
If I put

from functiontext.py import functiontext
``` and then put
```py
async def test(ctx):
  functiontext()
``` does that work? or do i have to def it in `functiontext.py` ?
#

like ```py
def functiontext():
await ctx.send("test")

brazen raft
#

Wow, what?

#

You have a function in another Python file which you want to import?

past ermine
#

yeah, to make my code a bit more organized

#

like what it should do is just to send("test")

brazen raft
#
# functiontext.py
async def functiontext(ctx):
    await ctx.send("test")
from functiontext import functiontext

async def test(ctx):
    await functiontext(ctx)
past ermine
#

hmm

#

let me try

brazen raft
#

The files have to be in the same folder

candid pier
#

Hi! I need help: I am create a slash command in cog file, and I did not know, how to realise it

slate nymph
#
      if args == hi:
            await ctx.channel.send("Hello")```
#

why isnt this working?

brazen raft
#

Put a comma after the *

past ermine
brazen raft
#

And put hi in quotes like "hi"

slate nymph
#

*,args?

brazen raft
#

Yeah

slate nymph
#

oh k

brazen raft
#

Also ctx.channel.send can be shortened to ctx.send

slate nymph
#

oh k thanks

#

also if i had to send both string and int how will i do it?

brazen raft
#

!f-string

unkempt canyonBOT
#

Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.

>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."

Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.

slate nymph
#

like phone number: 92828292901

river walrus
#

Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message

slate nymph
#

aww tysm

past ermine
#

@brazen raft it worked with the test command but doesnt with my help one

brazen raft
#

How does your help command look

past ermine
#
import discord
async def help(ctx):
  ""insert embed fields and all here""
  await ctx.send(embed=embhelp)
#

and ```py
from help import help
@client.command()
async def help(ctx):
help(ctx)

brazen raft
#

You forgot await before help(ctx)

maiden fable
#

!d discord.ext.commands.Bot.add_command And instead you can use this

unkempt canyonBOT
#

add_command(command)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/stable/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/stable/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/stable/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/stable/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/stable/api.html#discord.ClientException "discord.ClientException")
past ermine
# brazen raft You forgot `await` before `help(ctx)`

nope,
RecursionError: maximum recursion depth exceeded while calling a Python object

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

Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/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: RecursionError: maximum recursion depth exceeded while calling a Python object

#

nvm

#

it worked

#

can i do that for an

#

!d discord.on_message

unkempt canyonBOT
#

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

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/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/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
past ermine
#

@brazen raft ?

brazen raft
past ermine
#

i renamed it like the ```py
from help import help > from help import helpcmd

brazen raft
#

Maybe instead of passing ctx, pass the channel object.

#

Then you can use message.channel in the on_message event

#

For the functions

past ermine
#

ok thx

patent lark
#

can anyone send me the link to the source code of jishaku?

reef shell
#

!pypi jishaku

unkempt canyonBOT
reef shell
#

then goto thier github repo

patent lark
#

why didnt i just do that smh.

#

thank you.

reef shell
#

np

slate swan
#

hi is str

brazen raft
#

Yeah.

reef shell
rustic lily
#

i'm trying to make a piece of code execute every day based on utc, is there any easy way of doing this?

#

kinda like how @tasks.loop work

reef shell
#

Maybe using tasks.loop to loop task every 5 minute and check the time.. and if the time is your preferred time's range then execute the code block

rustic lily
#

suppose that would work

distant tree
#

is there a way to stream audio through a bot without ffmpeg?

reef shell
#

Bruh typing in mobile is shit

rustic lily
#

true

stiff nexus
#
Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-728216bb916d02a38e4f8263a0987926' coro=<PaginatorView.on_timeout() done, defined at /home/runner/paginator.py:170> exception=NotFound('404 Not Found (error code: 10008): Unknown Message')>
Traceback (most recent call last):
  File "/home/runner/paginator.py", line 175, in on_timeout
    await self.message.edit(view=self)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/message.py", line 1289, in edit
    data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 331, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
```how do i return this error?
brazen raft
rustic lily
#

so it dies about once per day

#

and @tasks.loop would reset every time the bot is back up

brazen raft
#

You can put your bot on AWS

#

On a virtual machine

rustic lily
#

but moneeyyyyyy

brazen raft
#

It's free

rustic lily
#

oh

#

h uh

brazen raft
#

If you put it on a Windows virtual machine you can SSH to it and Ctrl+C & Ctrl+V the folder of your bot

#

You'd have to install Python and all the packages on there, obviously

rustic lily
#

it would still have to go offline whenever i update the code

sick birch
#

you can reload code without shutting down the whole bot

rustic lily
#

yes but i'd like to be able to update the main file if needed

#

which i do from time to time

bitter depot
#

return ctx.author.id == 1234 or any(...)

manic blaze
#

can i grab the discord id of a channel by the name
im tryna make a command to make a channela nd send messages in it instantly
but idk how to get the id

brisk fiber
lyric moat
#

why this gives error?

        player = await YTDLSource.from_url(url, loop=client.loop)```
manic blaze
brisk fiber
#

same way as for any other channel— await new_channel.send(“stuff”)

manic blaze
#

aight bet

scarlet snow
#

and

#

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

Hi. why im getting this responed?

reef shell
#

seems like a list of api response(json)

slate swan
#

Hi

#

Why im getting this respond?

reef shell
#

can you show your code?

slate swan
#

Why i cant send pictures

reef shell
#

you can and it's better if you paste the code here with python formatting

#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

reef shell
#

or

#

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

lyric moat
#

why my play gives error?

@client.command
async def play(ctx, *, url):
  player = music.get_player(guild_id=ctx.guild.id)
  if not player:
    player = music.create_player(ctx, ffmpeg_error_betterfix=Ture)
  if not ctx.voice_cliet.is_playing():
    await player.queue(url, search=Ture)
    song = await player.play()
    await ctx.send(f'I have started playing `{song.name}`')
  else:
    song = await player.queue(url, search=Ture)
    await ctx.send(f'`{song.name}` has added to playlist')```
slate swan
#

()

#

@client.command()

lyric moat
#

lemme try that

#

did it but got this

slate swan
#

music isn't defined

#

read it before sending it

plucky shoal
#

Are you using ytdl?

slate swan
#

how can i join a guild off the id

#

not using a selfbot just in discord

#

Why im getting this respond?

slate swan
slate swan
reef shell
#

lol

slate swan
#

if you ask this without code again I1m pinging mods

slate swan
# slate swan stop asking this without the code
@bot.listen('on_message')
async def on_message(msg):
    if msg.author == bot.user:
        return
    if msg.channel.id == 885868705454628927:
        message = msg.content
        url = f"https://api.pgamerx.com/v5/ai"
        headers = {
            'Authorization': "Api_key",
            }
        params = {
            "message": message,
            "server": "main"
            }
        response = requests.request("GET", url, headers=headers, params=params)
        json = response.json()
        await msg.reply(json)
#

I'm known for not knowing json

reef shell
#

what's the issue?

slate swan
reef shell
#

you converted the response object to json format and replied to the context that's what i meant

slate swan
#

oh

slate swan
#

?

untold token
#

You need parse through it get whatever data you want

untold token
#

That's blocking

#

Use aiohttp

reef shell
slate swan
untold token
#

Well if you using aiohttp, it's quite different

#

As there are multiple way to make requests

reef shell
#

you might be wanting to reply to the context with that 'response' key's value

untold token
#
import aiohttp
url = "someapi.url"
# creating an Aiohttp ClientSession
# A Client session is basically an instance of an aiohttp client that you can use to make HTTP requests to an API
async with aiohttp.ClientSession() as session: 
   # using context managers, that will handle the ClientSessions aka creating and closing a Client session instance
   async with session.get(url=url) as resp: 
    # making an GET HTTP request to an API
   response = await resp.json() # let's assume the API is returning json data
   print(response) # printing the response returned from the API 

This is one way to send HTTP requests to an API

#

And

#
import aiohttp
url = "someapi.url"
# this is a much simpler method to make API requests without creating an aiohttp Client instance
# Aiohttp ClientSessions are recommended as you can create one session and use that session anywhere
# But in this case, you need use aiohttp.request method everytime you want to make a request to an API
async with aiohttp.request("GET", url=url) as resp: 
    # making an GET HTTP request to an API
   response = await resp.json() # let's assume the API is returning json data
   print(response) # printing the response returned from the API  

This one is another way to make requests, the difference is
That ClientSessions are sessions, this means you can create one session and use that session everywhere

slate swan
#

how can i do link blocker?

untold token
untold token
untold token
#

But you need to use regex to check links in a message

slate swan
untold token
#

First of all, you should use .listen() instead of .event (I will explain why)

Second, on_message event takes message object as an argument, not context, but in your ctx would be a message object and not a context object

slate swan
#

what now?

slate swan
untold token
#

For regex link checking, I would recommend you read this

untold token
#

Show your code with aiohttp atleast

full lily
slate swan
untold token
#

And message takes a message object,
So if you want actual content aka the message string,
You need to do message.content

#

So something like

slate swan
#
if isinstance(error, commands.MemberNotFound):
        embed = discord.Embed(description=f"{notcheck} {error}",color=color)
        await ctx.reply(embed=embed)```
#

how can i get just the members name

untold token
#
@bot.listen()
async def on_message(message):
   if message.author == bot.user:
        return # this checks if the message sent is by the bot or not, this check is important as on_message events consider bot messages as message too, `message.author` returns the member object of who sent the message 
  text = message.content # content aka message string ```
#

@slate swan read this and stack post, that much is enough to figure out what to do

#

And when you want delete message with links

slate swan
#

out of that

untold token
#

You need to use .delete() method

#

!d discord.Message.delete

unkempt canyonBOT
#

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

Deletes the message.

Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.

Changed in version 1.1: Added the new `delay` keyword-only parameter.
untold token
#

That is passed in the error handler

#

str(ctx.author) returns the username and tag of command invoker aka who ran the command

slate swan
#

i didn't touch much time in d.py, how can i make the bot send message if i have no ctx?

#

channel.send not works

#

message.channel.send

slate swan
slate swan
untold token
#

and .send() sends the message

slate swan
#

if "https://" in message.content

untold token
#

That would be bugged

slate swan
#

this only works if the message is explicitly just https://

#

ahhhh new error

untold token
#

That if statement will be satisfied and it will send the message

slate swan
untold token
#

^

#

await message.delete()

#

not message.author.delete()

#

I linked you the docs

slate swan
slate swan
unkempt canyonBOT
#

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

This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/stable/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/stable/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
untold token
#

No matter what its placement is

#

that's how the in keyword works

slate swan
#

if message.content == "https://" won't trigger if the message is not just "https://"

#

why would you do that

untold token
#

That's not a link?

slate swan
#

yes

#

there is something like message.content.startswith?

#

https://

slate swan
#

this isn't a link either

#

because it's blocked just https:// and nothing else

#

I would get a warning for just writing https://

untold token
#

Hm yes

#

But in your way, that would happen too

slate swan
#

then I wouldn't

untold token
#

Hmm

slate swan
#

that's what I thought

untold token
#

But that can be bypassable

#

I was just highlighting the flaw in your method

#

In both of the methods

#

That's why regex is recommended

slate swan
#

Trying to figure out why this isn't working

@client.event
async def on_ready():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            client.load_extension(f'cogs.{filename[:-3]}')
            print(f"{Color.GREEN}Loaded Cog: {filename[:-3]}{Color.RESET}")
    await asyncio.sleep(5)
    os.system('clear')
    print("Bot is online!")


#this part here is in my cogs file, named test.py

class test(commands.Cog):

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

    @commands.command()
    async def ping(self, ctx):
        await ctx.send("pong")


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

Shouldn't this work? In the terminal it says that the Cog "test" has loaded, however when I try to run the ping command it doesn't work

#

if isinstance(error, commands.MemberNotFound):
        embed = discord.Embed(description=f"{notcheck} {member} was not found in this server",color=color)
        await ctx.reply(embed=embed)

``` how can i get the member not found
untold token
slate swan
#

ctx.member didnt work

untold token
#

ctx.member won't work

#

.member is not an attribute of Context

#

.arguement attribute returns the member that was not found

slate swan
untold token
#

!d discord.ext.commands.MemberNotFound.argument

unkempt canyonBOT
untold token
#

Hmmm, do you have any on_message event?

slate swan
#

mhm

untold token
#

Do you have any on_message event @slate swan

slate swan
untold token
#

Ah okay

slate swan
#

Also I just did this

import discord
from discord.ext import commands

class test(commands.Cog):

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

    @commands.Cog.listener()
    async def on_ready(self):
        print("testing")


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

And got no output

untold token
#

Well it says the cog is loaded, you don't get command ping?

#

Hmm

#

Well, your code isn't wrong

#

And your cog us loading too

#

Maybe try changing file names

#

Like you have class and filename as test

slate swan
#

fair

untold token
#

I don't think it will change anything but try it

slate swan
#

Restarted my vscode instance somehow fixed it

#

🤷‍♂️

inland venture
#

if user_message.startswith() == 'how':

#

it said i need argument but what am i supposed to put?

lyric moat
slate swan
lyric moat
slate swan
#

And I think you mean ```py
if message.content == "how":
#epic code here

inland venture
#

if user_message.startswith() == 'how':
is not working

#

it said i need to add argument but i dont get it

slate swan
#

Where message is an argument

slate swan
slate swan
slate swan
slate swan
slate swan
lyric moat
#

i added it in music.py

slate swan
#

What's the error

upbeat vigil
#

hey can someone help me with this

lyric moat
upbeat vigil
#

idk whats wrong it usually works

slate swan
lyric moat
#

when i put music.py in a cog it gives error

slate swan
wicked atlas
lyric moat
#

from music import Player - this gives error when i tried

upbeat vigil
#

omg im actually so dumb

#

i need coffee

lyric moat
#

from music import Player this is in main.py

slate swan
#

Ok so within main.py you should have something that loads cog, you don't manually import it

#

Well you can

#

But this is just for the sake of making things easier

#
import os
import discord
from discord.ext import commands


@client.event
async def on_ready():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            client.load_extension(f'cogs.{filename[:-3]}')
            print(f"Loaded Cog: {filename[:-3]}")

This here upon bot connecting it will load cogs within your "cogs" folder

#

?

patent lark
upbeat vigil
#
#on mem join
@bot.command()
async def on_member_join(ctx, member):
  await bot.get_guild(882405229000282172)
  await bot.get_channel(888560564626948146)
  embed = discord.Embed(title="wlc <̶3̶", color=0x607d8b)
  embed.set_thumbnail(f"i.pinimg.com/564x/6f/a2/46/6fa246a6677075e79f5a2d8e426417d")
  embed.add_field(name=" <&roleid> • `<𝟛`",
                    value=f"""
  #roles & #req
  """)
  await ctx.send(embed=embed)``` if someone can tell me where i messed up that would be great
#

it shows 0 syntax errors but nothing happens on_member_join

full lily
#

you put @bot.command()

#

but it's an event

upbeat vigil
#

:O

#

SORRY lmao im rlly new to doing thi

full lily
#

no problemo

upbeat vigil
#

thank uu

full lily
#

also the get_guild and get_channel look redundant to me

#

unless you plan on using it later

upbeat vigil
#

so only get_channel() is nescesarry?

#

also is it client.event or bot.event

#

because bot.event didnt work

slate swan
upbeat vigil
#

i named it bot

#

and i get this error

full lily
#

without brackets

upbeat vigil
#

i see

#

thank you very much

icy seal
#
@self.event
async def on_message(message):
    print(self)

>>> <discord.Client subclass obj blah blah>

(When subclassing discord.Client) - why is self in the scope of this method? It's not explicitly passed through as an argument - what is event doing behind the scenes? Am I missing something obvious?

pure totem
#

is there a way to permanetly delete pymache.py? because everytime i run it pops up

#

and makes my bot go offline

bitter perch
#

but self refers to the current instance.

icy seal
#

i had just omitted some of the surrounding code. and that was the solution i was using, but i was wondering why my example there happens

#

python classes explicitly pass the object instance through a method as the first argument, like you said, self

bitter perch
#

It's an implicit pass

icy seal
#

yes, i realised that. i was wondering if anyone had an explanation as to why the behaviour is like this

bitter perch
#

events are just methods

#

and most just do nothing

#

even you use x.event deco, it just sets that method to the decorated func

icy seal
bitter perch
#

@icy seal

#

Just runs set attr

bitter perch
icy seal
#

That folder is very very unlikely to be causing issues with your code, and you shouldn't really need to delete it or prevent it from being genrated

bitter perch
#

You can prevent it with an environment variable

pure totem
#

oh ok

#

thanks i'll do that

bitter perch
#

PYTHONDONTWRITEBYTECODE=1

#

But there's 0 reason to do this.

pliant gulch
#

What does __pycache__ have anything to do with your bot going down?

#

I'm assuming you have a cog loader that loads __pycache__ probably

stark hearth
forest mortar
#

SO I have my friend that wants to use youtube_dl fr his bot, but when he sepecifies like from youtube_dl it don't works please help me.

stark hearth
stark hearth
forest mortar
#

ok