#discord-bots
1 messages · Page 479 of 1
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
Is it self.client or self.bot in your cog?
self.bot
then use self.bot.latency lol
oh
🤦♂️
ok thanks i am new to cogs
Make sure to multiply that otherwise
and probably round it out your choice tho

omg your ign is just genious
you have to pass in that kwarg into the Bot constructor
case_insensitive is for the bot class not command
my bot is case insensitive but idk how
well you can multiply it and use int()
this is the code he sent me
Check ur kwargs for the bot constructor
what that
the one where u defined client
guys what are the pros and cons of using a bot class or client class in discord py?
the Bot class has command features
stuff that allows you to make commands easily
!d lower
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!`.
have you named a file/folder discord in your project?
yes
it's bot.py
that is why, you need to have the actual discord module be the only thing called discord (try rename and see if it works)
ok it worked
yeah, try avoid naming things the same, it normally causes issues :)
When a role gets deleted, does the len(role.members) become 0?
how do i make the cmds not work in dms???
@commands.Cog.listener()
async def on_guild_join(self, guild):
await guild.create_category("Mailer")```
why doesn't this work
a error message?
one min let me reinvite my bot then
nvm thanks fixed it
how do i get a channel id in a specific category?
Is this a guild Welcome Command? Does it work? 🤔
uh
no
it creates a catogoray when the bot joins a server
Damn, I was going to ask, to copy it lol
Why?
creating guild welcome command is easy
!d discord.on_member_join
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.
^
i'm making a mailer bot
what if the bot doesn’t have permissions
smthing like modmail
Modmail?
also that’s a bad idea
ye
why
Why?
you should make it into a command instead
That’s true
when it's event it's automated
I’ve got a event, it doesn’t work 😥
name="Mailer"
!d discord.Guild.create_category
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.
@commands.guild_only()
this is a decorator from discord.ext.commands
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?
!d discord.on_command_error
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")).
use this event
where do I put it
example:
@client.event
async def on_command_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send(error)
ah thanks
so that can go anywhere in the code
and if that event happens that code will trigger?
yea is your error handler
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.
You need to either import it from discord, or just import discord and do
if isinstance(error, discord.MissingPermissions):
What's the problem with jt
I'm confused
Have you spelled it in all lowercase like you are sending here?
no
commands.MissingPermissions
Ah yes, thats a commands error
@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....
ctx is the suggested name of the context argument that is passed in to commands and some events
!d discord.ext.commands.Context
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.
so when I do something like ctx.send
raw_reaction_add only takes one argument
what does that mean
!d discord.on_raw_reaction_add
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.
That is shorthand for
ctx.message.channel.send
The Context object gives you the "context" in which a command happened
bruh thx
alright next thing
how do I get a function that runs everytime a message is sent
and get that message
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?)
on_message
!d discord.on_message
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.
Wdym
Like when Ive set a cooldown on a command
@commands.cooldown(trigger,seconds,type)
How do I reset it?
!d discord.ext.commands.Command.reset_cooldown
reset_cooldown(ctx)```
Resets the cooldown on this command.
this?
how can i make a command not show in the help menu ?
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 ^^
hidden=True kwarg beside the bot.command()
thanks
i also have help Shows this message in the menu..how can i remove that ?
idk about that lel
You can modify the help command itself, I forgot how tho
then can i just not show the No category category ?
uh not sure about that sorry
you can..but you gotta fully disable the help command and make another one
Uhm no, you dont have to disable it
Theres a kwarg in Bot() called help_command and as argument, you can give DefaultHelpCommand()
I did if message.channel.name == 'nice-place':
how do i make it so that I could make my bot work on all channels
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?
Add a for loop and iterate through guild.channels
@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
Whats the error exactly?
I can do in python the bot has count people in my server and refreshing this in 5 minutes?
Whot i can do it will the probelm is with @perms_enable_check(ban_members=True)
ban_members=True
!d Bot.loop.create_task()
No documentation found for the requested symbol.
Uhhh
Whats the error output???
The exception
hm
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'
You can use tasks
https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html
In on_ready
Wth?
But people says dont do it on ready?
Yes i know i do this and bot set status only one time and i don't know why his not refreshing :/
Theres no other way 🤦♂️ not that I know
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'
Just do it in on_ready
Ok ok wait a second
Do you mean, discord channels?
People say don't do it in on_ready, but you can, you just might ant to do a few things because on_ready is called whenever a bot logs in or re-logs into discord, so it's called multiple times occasionally
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
wut do i type?
ok
ye ye
someone maybe know why it isn't work correctly?
Might do a PR or two, depending on my time and work
use tasks.loop and wait_until_ready
Disthon, what does that do?
Amazing
ok
for channel in ctx.guild.channels:
if channel.name = 'xyz':
print(True)
It's like discord.py, discord.js and Sapphire (which is a Discord.js framework) fused their features
And gotten better
So youre basically trying to "when user has x permission, it should run the command"?
yes
I cannot find what perms_enable_check() does
i know the discord have got a check for it
@commands.has_permissions(ban_members=True)
i will send you full code
What’s this for?
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)```
if channel.name = 'xyz':
^
SyntaxError: invalid syntax
To iterate through every channel of the giild
i ended with error
Huh
@commands.command(usage=f"case [case]")
@perms_enable_check(ban_members=True)
async def case(self,ctx,case):``` it look like this
if channel.name = 'xyz':
^
SyntaxError: invalid syntax
!comparison
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")
Uhhhhhh why dont you just use @commands.has_permissions?
Ah yea I did only one =
if channel.name == "xyz":
<statement>
if channel.name == 'xyz':
My bad
also how do i define ctx
look on me full code
im a noob 😢
In a command
Where did you put that in?
Ah you got message
@inland venture replace ctx with message
message.guild.channels
It's not about defining ctx, it's about adding an argument.
def mydef(arg1)
lol
k ty!
Well Ive never used that so idk
uhhh
Plus I dont know what the code supposed to do
Hello ? someone can help me?
is it possible?
if ctx.message.author.guild_permissions.permisions: AttributeError: 'Permissions' object has no attribute 'permisions'
def perms_enable_check(permisions=None):
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:``` Why this return this error
what i can do?
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").
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)
Combine the values into a single string, and not a tuple
!strings
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.
Someone can help me?
@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
What
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...
It might be getting stuck in that while loop
how
update python
Make sure you have the latest version of discord.py
okay
3.9.7
okay
^ ? 
Your wording of your problem has made me very confused
mhm
Nvm ima try use if for 50+ strings then 
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

!rule 6 technically
??
???
???
dude what
what?
stop being so random lol
it is what it is lol
lol

ok
ok
Someone can help me?
What do you expect it to do tho
How do you know if it ain't working?

Calm down with the emoji, @vale narwhal
ok

Their whole personality revolves around that emoji lol
Haha. Anyways, let's drop this topic
If you want it to be online why do you need to put "discord.Status.online" tho
Wasn't it optional


Yeah ofc
Maybe setting the type kwarg is causing an issue
remove the type kwarg
If you didn't set multiple bot.change_presence why do you need to put it into tasks loop too
Also imagine making an empty API call
!d discord
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.
And sending two API calls in 10 seconds
Just straight use it in bot.event
You are inviting ratelimits
if you didn't set the multiple status
Yup, that's a huge mistake

Heya yerty
lmao
i want to make a bot command which will accept 2 arguments and will return one of them randomly... How do i make one
jokes aside, since you work with djs, will you be lending a hand with the project?
Im not familiar with djs
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)))

Gotcha
uh, you can do ctx, *args and then random.choice(args)
!ytdl
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)
Don't forget to import random too

10 API calls? Isn't changing presence something you do on the websocket
__import__("random").choice(args) there
???
I think they mean the fetch_guild
Yea one is that
Ok, I thought they were talking about change presence
that wont count context will it?
As that has no ratelimit since its on the websocket
???
Rather there is a queue I think or some other type deal
Wait, what you mean? Can I know more about what you are saying?
context is args 1 right?
changing presence isn't an HTTP request
Its done on the websocket
oh?
Ah, didn't know that. Thanks for telling!
You still don't want to be spamming it
Yea
He didn't even change multiple presence 
Why don't he put that straight into bot.event
coughs
coughs *
Haha
async def choose(ctx,*args):
await ctx.channel.send(random.choice(args))
How to get the Command object of a given command?
says choose isnt defined
import random
i did
they mean choose bro...
full traceback?

Wym
It say choose not random
oh yes
sure
Lmao my reaction was the damn same
lmao
Like I wanna reset the cooldown for a command, but therefor I need the object itself [ Command.reset_cooldown(ctx) ]
ctx.command
you can use Bot.get_command
Or how does that woooorkerk
and there is Context.command
Ahh cool thanks
You need a command decorator
missing () after bot.command
🤣 I love it when uvloop isn't available for windows and pip just tries to install it again but errors out
okay thanks
Ah I see
that’s where WSL comes in and saves the day
Well I got the Context so that should be enoughhh
Well, I don't use WSL much tbh...
Ah yes () 
But yea, that is a life saver
Just use linux on your main machine
I'm joking

But srs should check it out, fresh air from windows garbage
:stare: my mom gonna be like: Are you learning hacking or what
But yea, Windows 10 has many bugs and garbage, agreed
Bugs I could care less for, its the privacy
Let's keep this channel on-topic please guys
haha
!ot for general discussion
Off-topic channels
There are three off-topic channels:
• #ot0-psvm’s-eternal-disapproval
• #ot1-perplexing-regexing
• #ot2-never-nester’s-nightmare
Their names change randomly every 24 hours, but you can always find them under the OFF-TOPIC/GENERAL category in the channel list.
Please read our off-topic etiquette before participating in conversations.
Sorry Tizzy
!d discord.ext.commands.Context
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.
BTW, anyone here knows how to use asyncio to make my discord bot install a module (uvloop) automatically if it is hosted on linux?
Are you using poetry?
No venv for your bot??
any doc for args?
What do u expect
it is a param you define
Are you getting your bot ready for a VPS or something?
Yea
The VPS is linux, so uvloop is gonna work there
Ok, take a look at poetry really recommend, so you can install reqs easy
Ah ok
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
Thanks!
A discord bot focused on clean code and utility. Using the discord.py library - 0x42/pyproject.toml at master · an-dyy/0x42
Notice the markers
Thanks 😄
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?
I'm afraid we can't help with YTDL here as it violates YouTube's ToS and thus our #rules #5 @slate swan
Do you have a custom help command?
ok
how do i design my help command?
I didn't subclass, but made one with dropdowns and stuff
Ok, just asking because uvloop breaks any subclassed help command
Oh?
Since the help command in discord.py uses deepcopy
Which cython does not like
Which is what uvloop uses
Ah
👍
Also, have you ever tried converting the bot to Cython?
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```
Ah ok thanks
This help command looks jerk how do i modify it?
You can take my help command :^)
Or look at a guide for subclassing the help command
!d discord.ext.commands.HelpCommand you can subclass this
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.
!customhelp
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
I always forget that tag
sure
Me whose help command is divided between 3-4 files: :stare:
Probably because you didn't subclass
Way more compact to subclass since its all done for you already anyhow
aww thanks but such a big code for a help command?
Well, yea. But personally, I find using the deco easier
This is really small imo
bruh?
Its only 127 lines long
Mine is bigger than this iirc
I don't know... Lemme see
wow
Not counting the hyperview stuff*
Since its a util, and not strictly used on the help command only
Laughs in 64 lines
If I did it would still be under 300 lines
bruh.
hehe
mines only 98
What about @unkempt canyon :stare:
but the paginator it uses is about ~230 lines
Button paginators are pretty simple to make
mines paginated as well but not even close to that-
I could've made mine more compacted
formatting the pages were a pain ngl
Why would you handle formatting in a paginator?
splitting the list into pages
My paginator strictly paginates all the embed generation is done outside of it
I forgot what I was gonna do :stare:
Hence again, util not strictly used for one thing
Oh? How did you do that then
too lazy to rewrite the paginator to use buttons
Well buttons are slower than reactions, soooo 🤷♂️

working on a different project these days
Buttons are not slow at all imo, and to evenly compare the two you would need to factor in the ratelimts, which for reactions is pretty high
if message.channel.name == 'nice-place':
if user_message.lower() == 'hello':
await message.channel.send(f'Hello {username}!')
return
Yea that is true tho
what do i type to make my bot do it on all channels
since on_message is called every time a message is sent, you could remove your check for the channel name, and it would work in all channels.
I have no idea if the cached property even works to save time
I'm just hoping I won't need to keep calling get_command
I would say in this repo, the thing that took me the most time was the warn sql code
Eh? Lemme see
Use pg_orm
Wait, what does DO $$ do?
no clue I'm sql noob
Was worth it though, made my warn command super clean https://github.com/an-dyy/0x42/blob/a69d77e3acb901e317f1ec4f476c7992be7e0347/src/exts/mod.py#L105-L134
You only wrote that code
indeed. My help command is also just
@hunai.command(hidden=True)
async def help(ctx: commands.Context):
view = HelpView(HelpDropdown(ctx.bot, ctx.author == hunai.owner))
await ctx.send("HunHelp", view=view)
Clean 😄
Well do $$ is basically just the function
Ah ok
with my limited sql knowledge
dont we all
idk xD
Just make a mapping at this point
?
I actively avoid many if statements like that
h o w
So I just make a mapping
OPTION_MAPPING: typing.Dict[str, typing.Callable] = {"opt1": func1, "opt2": func2}
if user_choice in OPTION_MAPPING:
....return OPTION_MAPPING[user_choice](...)
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?
Yes you could
And pass it to mapping
Cool
Thanks a ton
BTW u using typing.Dict... Is it different from dict?
no
i mean yes
in <3.10 doing something like dict[str, Any] would result in an error
yes
yes
Well, actually
and I used to think I wrote the wrong syntax
In <3.10 you could import annotations from __future__
And use dict[..., ...]
As it turns all annotations into strings
right but dict[…, …] looks ugly
Yea, prefer typing.Dict[..., ...]
how should i import it?
like from where
also do i need to remove help command for that?
@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?
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
BTW andy have u tried converting a discord bot to Cython before?
why would you want to anyways
it says ..utills and..core cannot be resolved
lol
lol
How does the code look now
So it is responding twice
and returning an already responded error
I will fix it in some time lol
help me then
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
on_message?
!code
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.
wut
@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
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
Has anyone posted a queue music bot discord?
@patent lark
https://paste.pythondiscord.com/pumiqewato.rust
printing 2 twice but 1 isn't printed... any help?
hmm
Hey @pliant gulch (sorry for the ping), but mind helping me?
Problem tells me whatever option is, that it isn't in the mapping
Print out option I guess
Would mean option is None then
And how did u know option is not in the mapping, that is why its sending twice?
No, I knew because it wasn't printing 1
Seems like this is prob a user input error?
I mean, it is trying to send that same option twice, which I selected
actually why are you even executing those functions inside the mapping?
Seems like this should work fine, if inputted correctly
instead you could just remove await
eh, then how can I do?
grab the item from the mapping and then await it
ah ok
Hmm ok lemme try now
not it totally failed
like, it is trying to execute only one single method (the commands one)
isnt that what you want
It is executing that even when I select another option
what is your current code
so, no matter what you input it always executes 'commands'
Yea
If option is None it should not be passing the if statement
I select an option from the dropdown
None the less, calling commands
but then, how is the function getting called?
wait
Lemme see if I overwrote something
nope, I don't think so
anyone>
?
how do i change the role icon of a role using a discord bot?
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
That won't be possible with dpy since the feature was only just implemented into the Discord API and dpy isn't maintained anymore (so won't have these new features)
Alright, I'll take a more in-depth look later as I'm setting up my dotfiles right now
Thanks!
damn, thanks anyway
any autrole code I can use?
no
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
That's really old code
but no errors were given
!d discord.Member.add_roles
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.
and its Member.guild
bot.add_roles(member, role) --> member.add_roles(role)
member.server --> member.guild
ids are now integers not strings
@slate swan
ok thanks
not Member.server
Is the discordpy v2 beta worth using or should I seek a fork or maybe a diff lib?
PyCord is a fork. You won't have to change any code, just pip uninstall discord.py and pip install py-cord
Wrong reply, meant to reply @solid summit
I'll take a look at it
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")
yeah, to make my code a bit more organized
like what it should do is just to send("test")
# functiontext.py
async def functiontext(ctx):
await ctx.send("test")
from functiontext import functiontext
async def test(ctx):
await functiontext(ctx)
The files have to be in the same folder
Hi! I need help: I am create a slash command in cog file, and I did not know, how to realise it
Put a comma after the *
yay, tysm
And put hi in quotes like "hi"
*,args?
Yeah
oh k
Also ctx.channel.send can be shortened to ctx.send
!f-string
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.
like phone number: 92828292901
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
aww tysm
@brazen raft it worked with the test command but doesnt with my help one
How does your help command look
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)
You forgot await before help(ctx)
Use "" instead of **
!d discord.ext.commands.Bot.add_command And instead you can use this
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")
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
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.
@brazen raft ?
Yeah... Maybe name the function something else? help() is a built-in function in Python.
yeah, i fixed it
i renamed it like the ```py
from help import help > from help import helpcmd
Maybe instead of passing ctx, pass the channel object.
Then you can use message.channel in the on_message event
For the functions
ok thx
can anyone send me the link to the source code of jishaku?
!pypi jishaku
A discord.py extension including useful tools for bot development and debugging.
then goto thier github repo
np
if args == "hi"
hi is str
Yeah.
it is better than any other fork atm imo
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
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
suppose that would work
is there a way to stream audio through a bot without ffmpeg?
Bruh typing in mobile is shit
true
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?
Why as and not with?
well, my internet is kinda shitty
so it dies about once per day
and @tasks.loop would reset every time the bot is back up
but moneeyyyyyy
It's free
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
it would still have to go offline whenever i update the code
not if you use extensions
you can reload code without shutting down the whole bot
yes but i'd like to be able to update the main file if needed
which i do from time to time
return ctx.author.id == 1234 or any(...)
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
new_channel = await bot.my_guild.create_text_channel() new_channel is now a channel object of the new channel
why this gives error?
player = await YTDLSource.from_url(url, loop=client.loop)```
so how would I send a message in said new_channel
same way as for any other channel— await new_channel.send(“stuff”)
aight bet
you didn't imported the lib
and
!ytdl
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)
Hi. why im getting this responed?
seems like a list of api response(json)
can you show your code?
Why i cant send pictures
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.
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.
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')```
Are you using ytdl?
how can i join a guild off the id
not using a selfbot just in discord
Why im getting this respond?
you can't
stop asking this without the code
How much time will you ask the same q.
you should share the code to get help
lol
if you ask this without code again I1m pinging mods
@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
this is actually working the way you/your code wanted
what's the issue?
.
wdym
you converted the response object to json format and replied to the context that's what i meant
oh
That's a json response returned by the API
You need parse through it get whatever data you want
Btw don't use requests
That's blocking
Use aiohttp

if im importing that. what i need to change
Well if you using aiohttp, it's quite different
As there are multiple way to make requests
you might be wanting to reply to the context with that 'response' key's value
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
how can i do link blocker?
And the arguments like headers and parameters are both same in aiohttp and requests
You need an on_message event and then check for links
oh
ok
But you need to use regex to check links in a message
what i need to write here?
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
too complicated. Idk a thing about aiohttp
For regex link checking, I would recommend you read this
I don't think its really complicated
Show your code with aiohttp atleast
This sounds like "I am not willing to learn"
I cant finish that. Idk a thing about that
Message not messgae
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
my bad
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
@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
out of that
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.
You can get members through context
That is passed in the error handler
str(ctx.author) returns the username and tag of command invoker aka who ran the command
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
so just ctx.member
thx
message.channel.send()
message.channel returns the channel object where the message was send
and .send() sends the message
if "https://" in message.content
That if statement will be satisfied and it will send the message
just message.delete()
this if statement won't trigger when anything's after https://
!d discord.on_message
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.
if "https://" in message.content would trigger everytime that string is inside a string
No matter what its placement is
that's how the in keyword works
if message.content == "https://" won't trigger if the message is not just "https://"
why would you do that
that's the point
bru
So then
hey "https://" will be triggered too
That's not a link?
Yes
this isn't a link either
because it's blocked just https:// and nothing else
I would get a warning for just writing https://
but not if I write https://discord.com
then I wouldn't
Hmm
that's what I thought
Yes because in the OP's way, if the whole string = "https://" then it would send the message
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
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
MemberNotfound.argument
ctx.member didnt work
ctx.member won't work
.member is not an attribute of Context
.arguement attribute returns the member that was not found
use that?
!d discord.ext.commands.MemberNotFound.argument
The member supplied by the caller that was not found
Hmmm, do you have any on_message event?
mhm
.
Do you have any on_message event @slate swan
Nope, I can try make one?
Ah okay
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
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
fair
I don't think it will change anything but try it
if user_message.startswith() == 'how':
it said i need argument but what am i supposed to put?
error 😕
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Wdym
anyone?
And I think you mean ```py
if message.content == "how":
#epic code here
if user_message.startswith() == 'how':
is not working
it said i need to add argument but i dont get it
Where message is an argument
user_message isn't a thing I'm 90% sure
You need a setup function outside of the Player class
class Player(commands.Cog):
#your code
def setup(client):
client.add_cog(Player(client))
Wherever your code for this is, just put this outside the class, it should add the cog. Also you need to load the cog within main.py but I'm sure you already have done that
def setup(client):
client.add_cog(Player(client))
Does not work
You sure you added setup outside of your player class?
i added it in music.py
What's the error
hey can someone help me with this
idk whats wrong it usually works
Did you load the cog in main.py?
when i put music.py in a cog it gives error
You typed in asnyc, its async
async, notasnyc
from music import Player - this gives error when i tried
from music import Player this is in main.py
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
?
In cog?
spelt async wrong.
#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
no problemo
thank uu
also the get_guild and get_channel look redundant to me
unless you plan on using it later
so only get_channel() is nescesarry?
also is it client.event or bot.event
because bot.event didnt work
depends on what you named the variable
without brackets
@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?
is there a way to permanetly delete pymache.py? because everytime i run it pops up
and makes my bot go offline
this isn't a subclass. When subclassing you don't use the event deco
but self refers to the current instance.
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
It's an implicit pass
yes, i realised that. i was wondering if anyone had an explanation as to why the behaviour is like this
events are just methods
and most just do nothing
even you use x.event deco, it just sets that method to the decorated func
are you referring to the __pycache__ folder?
yes
It doesn't, it's just cached python bytecode
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
You can prevent it with an environment variable
What does __pycache__ have anything to do with your bot going down?
I'm assuming you have a cog loader that loads __pycache__ probably
__pycache__ is just an interpreter
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.
here is a why better explanation on it https://stackoverflow.com/questions/16869024/what-is-pycache
i cant help you with that because it breaks youtube tos, sorry
ok

