#discord-bots
1 messages · Page 950 of 1
Should I import it?
Or is it gonna be in a command
Why should I if its useless?
What does it do?
Yes
Yea??
I don't need to write
@slash.slash(name="", description="")?
Can you please show me some examples?
slash = SlashCommand(bot, sync_commands=True)
How should I fix the error?
name 'SlashCommand' is not defined
@commands.has_permissions(ban_members=True)
@client.command(name="ban")
async def ban(ctx, member : discord.User, *,reason = "No reason was provided"):
banhammer=":ban_hammer:"
reason = "".join(reason)
embed=discord.Embed(title=f"{member} Banned from {ctx.guild.name} {banhammer}", description=f"\nModerator:{ctx.author.mention}\nreason: {reason}\nTime: ∞",color=0x34568B,timestamp=ctx.message.created_at)
embed.set_thumbnail(url=member.avatar_url)
embed.set_footer(icon_url=member.avatar_url, text=f"{member.name} | {member.id}")
embed1=discord.Embed(title=f"{member} Banned {banhammer}",description=f"\n Moderator: {ctx.author.mention}\nReason: {reason}\nTime: ∞",color=0x6699ff,timestamp=ctx.message.created_at)
embed1.set_thumbnail(url=member.avatar_url)
embed1.set_footer(icon_url=member.avatar_url, text=f"{member} | {member.id}")
embed2=discord.Embed(title=f"You have been Banned from {ctx.guild.name} {banhammer}",description=f"\n Moderator: {ctx.author.mention}\nReason: {reason}\nTime: ∞",color=0x6699ff,timestamp=ctx.message.created_at)
embed2.set_thumbnail(url=member.avatar_url)
embed2.set_footer(icon_url=member.avatar_url, text=f"{member} | {member.id}")
await ctx.send(embed=embed)
await member.send(embed=embed2)
await asyncio.sleep(0.1)
await ctx.guild.ban(member, reason=reason)
print(f"{member} banned from {ctx.guild.name}")
Nothing error, but the bot never ban.
yeah but nothing error
Thank you so much!
@bot.command()
async def on_ready():
print("Bot is ready!")
How can I fix this? What attribute should I use?
How did you define the object 'Client'
I didn't define it
:D
How should I define it?
Where did you define the 'bot'
Nowhere
intents = disnake.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix=".", intents=intents)
when I copied this code to my new computer the %s turned blue. Does anybody know why this is happening because of my old computer it was working. And now it wont run
can you do await message.remove_reaction(tuple_of_emojis)
How Do I Get User Reaction Like If he React ⬅️➡️ so my page get edited can i do it?
where do you do this?
not the right channel
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/master/api.html#discord.Emoji "discord.Emoji").
If the reaction is not your own (i.e. `member` parameter is not you) then the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission is needed.
The `member` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") instead of `InvalidArgument`.
@quaint epoch I don't think so
how do i get my bots name and tag?
!d discord.Client.user
property user```
Represents the connected client. `None` if not logged in.
Ok thanks
returns a client user so you can do client.name and client.discriminator
or convert this to str
iirc that gives the name and tag too
But what if I use bot = commands.Bot(command_prefix = "-")
then you just replace client with bot
Ah ok that makes sense thanks 😄
ok sorry thx
?
why not just use buttons?
I dont know about that
if u go through an short example i try
its better overall and depending on your lib some of them have examples on their github repo
Yeah I know yet they give only codes but how the code works they dont tell
what lib do you use
well yeah its just subclassing the View class
🗿 i'm pretty sure the docs tells you
are you in dpy 2.0
not really 
1.7.3
me subclassing both button and view
upgrade to 2.0 pls
yeah
ewwwww
discord.gg/dpy #guild-news to see how to upgrade @lyric apex
i don't check docs anymore i check src
shut up please
i know it's a cursed way, but it works for my needs

Ok
i just subclass view
why upgrade to master tbh i wouldnt
How to set up sqlite for my bot?
just use aiosqlite and read their docs lol
why
master supports most of the newer api stuff
@fading harness after upgrade there is chance that some of my codes will give error ryt?
which disnake already does which they dont have asyncio breaking changes and their lib is actually stable for any user?
yes allot

alr , how to make a main.sqlite file is in the docs too?
yeah.
it is a lot lot of breaking changes, ask people in dpy since i havent parcipated in a long time so i couldnt remember
especially the Context manager for bot
tbh it's much easier to subclass both 
only time i would subclass buttons is to have default values
whats the cog.listener command for (got disconnected)
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
this?
Is there any error instance for cooldown
an error that would be raised?
No The bot Send The Message Command On Cooldown Not Print
so you want to send a message if the command is in cooldown?
!d discord.ext.commands.CommandOnCooldown
exception discord.ext.commands.CommandOnCooldown(cooldown, retry_after, type)```
Exception raised when the command being invoked is on cooldown.
This inherits from [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError")

the dir is so confusing
nah nah i wanna make a listener for if the bot got disconnected
well, i have over 30 commands that requires buttons, i don't want to create a new buttons for all, it's just easier to call the subclassed button and just give a name and emoji if needed
just use the listenr and on_disconnect
thanks
!d discord.on_disconnect
discord.on_disconnect()```
Called when the client has disconnected from Discord, or a connection attempt to Discord has failed. This could happen either through the internet being disconnected, explicit calls to close, or Discord terminating the connection one way or the other.
This function can be called many times without a corresponding [`on_connect()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_connect "discord.on_connect") call.
ik that
actually nextcord also does that and i was the person who wrote the implementation for async cog loader without making a breaking change
does it will show the seconds remaining for cooldown to end?
you mean making the cog load method a coroutine?
yeah, without making bot.load_extension a coro
how is that not breaking?
you would need to add it to a coroutine if you want to use it?
should be aswell shouldn't it
really is that easy
it's not all about knowledge I see
sometimes it's just about the idea
where and how do you store those
things that you have to remind the user about
oh with asyncio.sleep?
Ig you have to store them
no
but yeah, a dict like that would do for sure
so kinda yes
I'd use the user's id as the dict key and store the stuff in a tuple as a value
since people can have multiple
remind's the dict?
probably
then yes
what
I don't know what your dict's name is
but it surely doesn't matter as long as you know it
or json

consider a database @slate swan, not necessary but useful for the future
maybe if you wanna practice
no
those are free
everywhere
@commands.Cog.listener(name="on_disconnect")
async def on_disconnect(self):
print("lmaooo")
self.bot.clear()
This doesnt work does anyone know why
Help
Well no,Database is free to use and what I would suggest is usin SQLite(the img above also has it)
@slate swan
Unindent the event decorator and the function
i forgot to add context but as disconnect i meant if the user kicked the bot from the vc
ill pay u if u help me fix a bot in dms
Error getting ID for uma
Ignoring exception in command watch:
Traceback (most recent call last):
File "C:\Users\emanu\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "latest.py", line 1065, in watch
url = f"https://i.instagram.com/api/v1/users/{targetssid}/info/?from_module=feed_timeline"
UnboundLocalError: local variable 'targetssid' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\emanu\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\emanu\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\emanu\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'targetssid' referenced before assignment```
whoever helps me fix this il pay^
Paying for help is against the rules
!d intents
Why is my slash command not showing? Its basically like the /insult one but a little bit modified
how do i enable member intents 😭
oh found it
Lol
@slate swan that looks like some bad indentation there
I would assume that's why there are so many yellow errors
Because it's all indented incorrectly
ok but then why does the insult command work? its basically the same
No clue, but those errors are not a good thing. Right click them and see what it's telling you to do
should i make a REPL command for my bot 
I request you to not ping me randomly, please?
how would i know if the bot got disconnected from vc by a user? (through right-click and disconnect)
idts you can figure that out
idts?
i dont think so
damn alright
guys
how to make a bot in such a way that if interaction.response happens then oppen a text channel in the guild
What does this mean?
what
ctx is a Remind object
Yeah, but don't get how to fix it or whats wrong if you get me
def load_extensions(self, path: str = './cogs'):
files = Path(path).glob('**/*py')
file_pattern = compile(r'[^_](.*)[a-zA-Z0-9].py')
for file in files:
if file_pattern.match(file.name):
_path = f'{path[2:]}.{file.name[:-3]}'
self.load_extension(_path)
logging.info(f'Extension loaded: {file.name}')
tryna sub class commands.Bot but im having this prob
E:\Computer Science\Python\Game\Discord\Oxygen\bot.py:43: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
self.load_extension(_path)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
this happens and none of the cogs load, is load_entensions supposed to be async?
do intents = discord.Intents.all()
yeah i noticed
Wait wut since 2hen load_extension is async
Try awaiting the load extension funcs
tried it, still doesn't work
getting the same warning
Await this
self.load_eextensions right? did that already
the method is a coroutine now
oh yea it is
embed.set_footer(text="If you have any questions, suggestions or bug reports, please join our support Discord Server: link hidden", icon_url=ctx.author.avatar_url)
``` Anything wrong here huh
just checked the src
Yeah make that function async, and await the self.load_extension
And then await self.load_extensions
async def load_extensions(self, path: str = './cogs'):
files = Path(path).glob('**/*py')
file_pattern = compile(r'[^_](.*)[a-zA-Z0-9].py')
for file in files:
if file_pattern.match(file.name):
_path = f'{path[2:]}.{file.name[:-3]}'
await self.load_extension(_path)
logging.info(f'Extension loaded: {file.name}')
the way im calling
bot_instance = Bot.create()
bot_instance.load_extensions()
bot_instance.run(constants.Bot.token)
still getting the same warning
Show the whole function
Sure
@commands.command(case_insensitive = True, aliases = ["remind", "remindme", "remind_me"])
@commands.bot_has_permissions(attach_files = True, embed_links = True)
async def reminder(ctx, time, *, reminder):
print(time)
print(reminder)
embed = discord.Embed(color=0x55a7f7, timestamp=datetime.utcnow())
embed.set_footer(text="If you have any questions, suggestions or bug reports, please join our support Discord Server: link hidden", icon_url=ctx.author.avatar_url)
seconds = 0
if reminder is None:
embed.add_field(name='Warning', value='Please specify what do you want me to remind you about.') # Error message
if time.lower().endswith("d"):
seconds += int(time[:-1]) * 60 * 60 * 24
counter = f"{seconds // 60 // 60 // 24} days"
if time.lower().endswith("h"):
seconds += int(time[:-1]) * 60 * 60
counter = f"{seconds // 60 // 60} hours"
elif time.lower().endswith("m"):
seconds += int(time[:-1]) * 60
counter = f"{seconds // 60} minutes"
elif time.lower().endswith("s"):
seconds += int(time[:-1])
counter = f"{seconds} seconds"
if seconds == 0:
embed.add_field(name='Warning',
value='Please specify a proper duration, send `reminder_help` for more information.')
elif seconds < 300:
embed.add_field(name='Warning',
value='You have specified a too short duration!\nMinimum duration is 5 minutes.')
elif seconds > 7776000:
embed.add_field(name='Warning', value='You have specified a too long duration!\nMaximum duration is 90 days.')
else:
await ctx.send(f"Alright, I will remind you about {reminder} in {counter}.")
await asyncio.sleep(seconds)
await ctx.send(f"Hi, you asked me to remind you about {reminder} {counter} ago.")
return
await ctx.send(embed=embed)
Now bot_ instance.load_extensions await it
how do i run it then? asyncio.run?
so await bot_instance.load_extensions
i cant await outside async func
Load extensions within the setup hook
whats that?
z
Which is asynchronous
Yea
@tough lance
It’s an async entry point into your bot where you can do setup tasks like database connection, aiohttp, extensions, etc
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
alr tsym
paying for som1 to fix a discord bot for me. Dm me asap need done today!
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
Anyone else?
not that one
.
!rule 9
against the rules we can only help you. for free ofc but you cant offer jobs
We can help you fix it for free, which is better than wasting money for someone else to fix it for you 🙂
fr who waste money on discord bots
Honestly

theirs so much devs which do it for free which are devs which are not bad nor good but theirs always that trash dev who wants money, my point is dont waste your money in discord bots
erm not tryna spam it sorry but anyone please 
ctx is self you need to add another argument
so it would be self, ctx, ...
a paid job and they always start by naming their bot class instance client
One of the reasons bot dev is a minefield
If I paid someone to make me a bot and they have client = commands.Bot I would ask for a refund faster than you can blink
It’s really funny seeing all the “full stack & experienced” people on fiver making horrible bots
bro it always makes me mad when i see could make you a bot for 5 or more dollars and their code is horribly done
Eyup
bro its always fiver or a trash discord server marketplace 💀
oh my god I am so stupid....
I legit forgot to add self...
you arent
I guess it’s profitable since if you’re buying a bot you don’t know how to code one anyway
I mean if I forget to add self
Time to code bots for 99 cent and shark people
Maybe we should buy 4 bots and judge how well it’s done. That would be funny
its so easy to browse for devs that actually know what to do
Yeah haha
bro frrrr
the funny thing is that they have the early bot dev emoji in their status and they always have the semi nsfw pfp and they always advertise their servers on their bio💀
Lmao
Let me make that my profile rq
bro
anyone kno how to print ansi art?
not really related to discord bots but oh well
Time conversion goes brr
Use some lib for parsing time or this converter #discord-bots message
Or make your own but the current time conversion is sus
buy this
and see if it's worth almost 300 Euros 💀
yeah, tf so overpriced for something i can do it myself
"Advanced Economy System"
idk feels over lmao
maybe i should start doing bots for money too, if you can earn that much money for a single bot lmao
"I will create a discord bot in python and pass you the source codes" It makes me think if there are people coding a bot for you but not pass the src
I thought about that too but I'm too lazy to decorate my profile page + fiverr is blocked in russia so gg
We're being discriminated by IT companies 💀
Can't even find normal hosting now
Find russian hosting 💀
Perfect scheme would be having multiple code templates, just updating texts and IDs and sending them to the clients
I made a templating tool a while back that would theoretically make doing that insanely easy lol
I made a similar thing in the "special outdated version" of some bot
It has a setup file which just asks for IDs of certain channels and there yall go
yeah that's what i was thinking about, when you know you have some experience with certain type of commands you just make use of old code and update them if necessary
who would buy that...
Bots that include bots
lmao
it's not too late to make it be a thing if it's not
The only issue is the lack of computing powers
people who have no idea about coding at all
I don't think it's hard to do if you know how to use docker
fr
and what's more stupid, they be adding you just 2-3 "advanced" commands and that's all
500$
his basic package is 150 🤣
I wonder if anyone has purchased anything there
from this person purchased 125 lol and has a 5 star rating
I'd say 5-10$ is a fair price for an average bot, not higher
But in fact they can be free
🗿 if you want a job to be done perfectly, do it yourself
They will have that 5 star rating until their json database breaks down 👌
lmao
Sometimes I just think...
tbh, i paid just one time for this when i was a total beginner like 1 year ago i think, i paid a guy 5$ to make me an economy system, just that, but in exchange he reworked all my code and helped to set up a mysql db too lmao
and fun fact, i never used the economy system because it's written in classic prefix command style
and 2 months ago i rewrite all my code myself anyway because i switched to slash commands
These people charge more than a 100 USD for making bots, lmaooo I can charge like a 50 USD and be like: Here is the compiled executable, just run the exe and the bot will work
anyone know why its doing this instead of sending the file?
And the templates are already ready, they just copy paste code 😔
send(file=file)
don't do send(file)
im doing:
webhook.send(content=discord.File("information.png"))```
Use the file kwarg
it gives the same result
show code
this is the code lol
heres the full
import discord
from discord import Webhook, RequestsWebhookAdapter
webhook = Webhook.from_url("", adapter=RequestsWebhookAdapter())
webhook.send(discord.File("information.png"))```
ah ok that worked
i didnt need to
“Pay me 50 USD for an advanced bot” inb4 reskinned red bot
Lmao
ty btw 👋
is okay
im trying to code my own Discord Music bot
!ytdl thanks
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)
how do you know they don't have a license ?

So guys, any ideas of interesting APIs that i can integrate in a bot ?
Hello, does anyone know how do I execute a command inside a command? If you get what I mean by that...
nested commands?
well I believe you can use Context.invoke()
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function...
well I was asking if that’s what you wanted
but Context.invoke() allows you to invoke a command
that's probably going to get the job done
ok 👍
anyone know how to send multiple embeds at a time using webhook.send()?
Payments with stripe maybe
Imagine spending money for a music bot 👏👏👏
Imagine not composing your own music for a music bot
Hmm
hm
imagine not creating your own language for your bot
Is that a challenge
imagine making a bot
yes, i doubt you can do it anyway
I mean
i shall make a twitter bot spamming n word at black images
It’s pretty simple, I could make it pretty simply but it would have only a few keywords
I just need to read the code, lexical stuff then interpret into python code
!e
puts = print
puts("Hello World!")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
Hello World!
Ruby 
OH MAH GAWD

!eval e=π*7
print(e)
@gaunt ice :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'π' is not defined
ok....


that pfp tho.....
kats.....
!e e=1/9+3
print(e)
@gaunt ice :white_check_mark: Your eval job has completed with return code 0.
3.111111111111111
no is not
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
what to do???
show code lol
anyone have the gitpost about discord py being revived?
means that the command isnt existing
its already running?
hmm idk
Like a month or something ago
hmm
found it
hey guys, so I'm working on a reaction roles code for my bot, this is what I've done so far,
@client.event
async def on_reaction_add(self, payload):
if payload.message_id == mid:
guild_id = payload.guild_id
guild = discord.utils.find(lambda g : g.id == guild_id, client.guilds)
role = discord.utils.get(guild.roles, id=rid)
if payload.emoji.name == "PinkHrt" and role not in payload.member.roles:
await payload.member.add_roles(role)
the bot doesn't respond upon adding a reaction and doesn't return an error either
what is mid
message id
where is that defined?
import discord
from discord.ext import commands
import youtube_dl
class music(commands.Cog):
def init(self, client):
self.client = client
@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("Join nem Channel du dulli!")
voice_channel = ctx.author.voice.channel
if ctx.voice.client is None:
await voice_channel.connect()
else:
await ctx,voice_client.move_to(voice_channel)
@commands.command()
async def disconnect(self,ctx):
await ctx.voice_client.disconnect()
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
YDL_OPTIONS = {'format': "bestaudio"}
vc = ctx.voice_client
with youtube_dlYoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'] [0] ['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
@commands.command()
async def pause(self,ctx):
await ctx.voice_client.pause()
@commands.command()
async def resume(self, ctx):
await ctx.voice_client.pause()
def setup(client):
client.add_cog(music(client))
!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.
💀
we don't help with music bots
damn it
!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)
my problem is that the bot doesnt join the channel
when i type $join it says command join wasnt found or something like that
@urban shell have you tried using on_raw_reaction_add?
!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/master/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/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
this uses payload, which it looks like you are trying to use
!d discord.on_reaction_add
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
Whereas this uses reaction and user
Mind helping? I can't import discord_slash
I think slash commands work now with from discord import app_commands
I tried installing discord_slash, but this is what I get;
Oh, will try it, thanks
make sure you have the latest version of the discord module though
Hold on I think I'm wrong
aaaaaa
my bad
tysm
just me being dumb at midnight
No problem!
Hm?
the def init the @commands.command() must be same vertical line
Can you help bud?
How can you send in the same channel as an interaction
interaction.channel.send works.
Yeah
I was figuring out how to install the new package
python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py
What does this mean?
pip install that in your terminal and you'll have the 2.0 version of the discord module, so you can use app_commands
@discord.app_commands.command(*, name=..., description=...)```
Creates an application command from a regular function.
hey, im new is there anything wrong with this?
if it's underlined in red, there's usually an error
Anyone working with discord.py new app_commands?
Anyone 
Remind.author somewhere in your code?
there's no Remind.author
imagine Remind = ctx
nope what exactly
well that's pretty much what your error says
yeah thats weird
Sure
So not just line 21 the whole command.
I am
Something on ..**.**author
Is it good? Looking at it now it's pretty weird.
Since it wants you to define a client instead of bot then make a command tree.
embed.set_footer(text="If you have any questions, suggestions or bug reports, please join our support Discord Server: link hidden", icon_url=ctx.author.avatar_url)
``` line 21
ye?
So not just line 21 the whole command.
commands.Bot comes with a tree
i see no problem in the footer, so the problem should be above ig
Ah ic
!d discord.ext.commands.Bot.tree
property tree```
The command tree responsible for handling the application commands in this bot.
New in version 2.0.
That is not explained really well, might use Client anyways since bot has literally no use now anyways.
Well I guess mention prefix?
Also cogs
client has cogs
@cloud dawn
It doesn’t
@cloud dawn I just started working with app_commands
Angry client noises.
@hoary cargo
that's pretty cursed to alternate ifs and embed fields like that
I'll make my own then ig
erm so what now
I'll figure it out thanks for the tree one.
why does this error come up? And how to fix it?
@app_commands.command(name='dc')
@commands.has_permissions(manage_guild=True)
async def _dc(self, interaction: discord.Interaction):
"""Stops playing audio and clears the queue."""
await interaction.voice_client.disconnect()
await interaction.response.send_message("dc")``` ```py
Ignoring exception in command 'dc':
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 457, in _invoke_with_namespace
return await self._callback(self.binding, interaction, **values) # type: ignore
File "C:\Users\culan\OneDrive\Desktop\echo slash\cogs\testmusic.py", line 541, in _dc
await interaction.voice_client.disconnect()
AttributeError: 'Interaction' object has no attribute 'voice_client'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\tree.py", line 998, in call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\app_commands\commands.py", line 476, in _invoke_with_namespace
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'dc' raised an exception: AttributeError: 'Interaction' object has no attribute 'voice_client'``` how can i fix this??
Good luck
ctx.author.send
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
ty
hey, when i add code for an autoemoji reaction thing the rest of my commands dont work
is there a way i can prevent this
Whats the ctx though ctx.member.send?
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
@junior verge
cant you just tell it lol
I am?
ctx.what then?
It's right here
How can I make a bot say something in a channel during the on_ready client event?
You don't
i would understand if in console, but in chat 
I legit dont get it lol
You could do it in on_connect
docs always confuse me
!d discord.on_connect
discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") for that.
The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") also apply.
And how could I do that?
It's not recommended to do it in on_connect but if you had to you could
ctx is your instance of the discord.ext.commands.Context class
message.author.send
The author attribute of the Context class returns a discord.Member object
This discord.Member object has a send() method
So ctx.message.author.send
@client.command()
async def Hello(ctx):
await ctx.reply("Hallo")```
If I have this how do I make it reply with your tag or whatever
!d discord.ext.commands.Context.author
Union[User, Member]: Returns the author associated with this context’s command. Shorthand for Message.author
!d discord.User.discriminator
The user’s discriminator. This is given when the username has conflicts.
foRole = await getRole('Franchise Owner')
gmRole = await getRole('General Manager')
hcRole = await getRole('Head Coach')
customRole = await find_by_name(role, ctx.message.guild.roles)
emoji = await find_by_name(role, ctx.message.guild.emojis)
for member in ctx.guild.members:
if foRole in member.roles and customRole in member.roles:
FO.append(f"{member.mention}``{member.name}``")
if gmRole in member.roles and customRole in member.roles:
GM.append(f"{member.mention}``{member.name}``")
if hcRole in member.roles and customRole in member.roles:
HC.append(f"{member.mention}``{member.name}``")
if customRole in member.roles:
CUSTOM.append(f"{member.mention}``{member.name}``")
if not FO:
FO = ['``⌬ | There is no FO ``']
if not GM:
GM = ['``⌬ | There is no General Manager``']
if not HC:
HC = ['``⌬ | There is no Head Coach ``']
if not CUSTOM:
CUSTOM = ['None']
if customRole.name not in team:
await ctx.send("**__Not a NFL Team Try And Use The Emoji__**")
else:
embed = discord.Embed(title=f'Role {customRole.name} Roster', description=f"{emoji}{customRole.mention}" , color=customRole.colour)
embed.add_field(name=f'Team Staff:', value=f">>> FO:{', '.join(FO)}\n GM:{', '.join(GM)}\nHC: {', '.join(HC)} ", inline=False)
embed.add_field(name="Players", value=f"{customRole.name} Players: \n >>> {', '.join(CUSTOM)} ", inline=True)
embed.set_author(name=f"{ctx.guild}", icon_url=str(ctx.guild.icon))
embed.set_thumbnail(url=str(emoji.url))
embed.set_footer(text=f"Roster Count:\n {len(CUSTOM)}/30 \n")
await ctx.respond(embed=embed,ephemeral=True)
```?
bot responds with interaction failed
pycord btw.
Traceback (most recent call last):
File "C:/Users/PycharmProjects/MusikBot/main.py", line 10, in <module>
cogs [i].setup(client)
AttributeError: module 'music' has no attribute 'setup'
maybe someone help :D
omg I always have this error type as well that's so annoying
what am i supposed to do man
im searching on the internet to find some solutions but I can't find a solution to a special error
and I don't remember what was the error precisely 💀
await discord.add_roles("2010 Member")
AttributeError: module 'discord' has no attribute 'add_roles'
not in cog
it should be "member"
oh
!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/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Just add an arg in ur command and typehint it
For example member: discord.Member
Btw what are u trying to do?
Add a function called setup in ur file
No
Btw what are u trying to do?
give roles on join
Ohh
Can i see what ur event looks like
It should have an argument
@client.event
async def on_member_join(member):
if member.guild.id != 95750864343484261507123: return
welcome = client.get_channel(9589434427683050410014)
await welcome.send(f"Welcome to the server {member.mention}!")
await member.add_roles("2010 Member", member:discord.Member)```
im so dumb
just remove member: discord.Member
why would i add that into the await
im dumb asl
everybody knows arguments go in async lol
and iirc add_roles doesnt work with roles name
so i need to do id
Just add role = client.get_role(UrRoleId) and in the add_roles
async def on_member_join(member):
if member.guild.id != 957508684261507123: return
welcome = client.get_channel(958927683050410014)
joinrole = client.get_role(957834796325830656)
await welcome.send(f"Welcome to the server {member.mention}!")
await member.add_roles(joinrole)```
like that?
Yes
now that leads to my next question.
whats ur next question
@commands.command(help = 'Ban a member!')
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, member : discord.Member = None, reason=None):
if member == None:
await ctx.reply("Please mention a user!")
else:
await member.ban(reason = reason)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} banned!**", color=discord.Color.green())
logs = commands.get_channel(958932470710030431)
await ctx.send(embed=embed)
await logs.send(f"{ctx.author.mention} has banned {member}!")```
once i ban, it doesnt send logs and said get_channel is not an attribute
I really need help, I can't move on without figuring this out :(((
It should be client
Not commands
If you're using cogs
Command raised an exception: AttributeError: module 'discord.ext.commands' has no attribute 'get_channel'
oh
Since you're using cogs
self.client
Ye
Im not that good but ye whats ur issue
member is not defined
define it. who did you give the role?
You gave it to user. So don't use member, use user
oh yea
lmao i promise im not dumb, i just keep messing up on simple shit
await logs.send(f"{ctx.author.mention has manually removed {member}'s mute!")```
not sure how this is unterminated
well i know its the apostrophe but how do i get around it
{ctx.author.mention has manually removed {member}
U need }
See anything wrong with this?
Yo my brain is dead can u check #help-pear
Same 
Argggg
Command raised an exception: AttributeError: 'Commands' object has no attribute 'client'
I'm not far enough in my knowledge to know how to fix this
Code?
update when
@commands.command(help = 'Temporarily mute a member!')
@commands.has_permissions(kick_members=True)
async def mute(self, ctx, member: discord.Member,time):
muted_role=discord.utils.get(ctx.guild.roles, name="Muted")
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
tempmute= int(time[0]) * time_convert[time[-1]]
await ctx.message.delete()
await member.add_roles(muted_role)
embed = discord.Embed(description= f"✅ **{member.display_name}#{member.discriminator} muted successfully!**", color=discord.Color.green())
logs = self.client.get_channel(958932470710030431)
await ctx.send(embed=embed)
await member.send(f"You were muted in {ctx.guild.name}!")
await asyncio.sleep(tempmute)
await logs.send(f"{ctx.author.mention} has muted {member} for {tempmute}!")
await member.remove_roles(muted_role)
await logs.send(f"{member}'s mute has now expired!")```
would it be just "self.get_channel" instead of "client.self.get_channel"
Its "self.client"
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
well its in a cog
@slate swan
😔
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
Then u need CooldownMapping ig
error doesn't match tthe code?
@abstract kindle check this
logs = discord.get_channel(958932470710030431)
@slash.slash(name="Demand", description='Demand from a team')
async def demand(ctx, role: discord.Role):
await Role.remove_roles(role)
embed=discord.Embed(title="Demand Completed", description=f" You have Demanded from {role.mention}")
await ctx.send(embed=embed)
role2 = ctx.guild.get_role(959281609117413376)
await user.add_roles(role2)```
so would it be this?
Its client
what is this? await Role.remove_roles(role)
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
remove role when u run cmd
brah
basically
logs = discord.client.get_channel(958932470710030431)
If you have client = discord.Client(...) then you have your Client object
No bro, go look at the top of your code
"""Moderation commands!"""
def __init__(self, bot):
self.bot = bot```
then use self.bot.get_channel
yeah

still dont work
Command raised an exception: AttributeError: module 'discord' has no attribute 'bot'
Check #help-pear
That's setup with in your main file where you setup your Bot object
you mean discord.ext.commands.Bot ?
He's trying to do discord.bot.get_channel
ah lmfao
what library are you using?
So I'm getting this error```py
Failed to Load Extension cogs.code_snippets
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\bot.py", line 791, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\cogs\code_snippets.py", line 53, in <module>
class CodeSnippets(
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\cog.py", line 147, in new
new_cls = super().new(cls, name, bases, attrs, **kwargs)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 733, in init_subclass
cls.discord_app_commands_group_name = validate_name(name)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\app_commands\commands.py", line 144, in validate_name
raise ValueError('names must be between 1-32 characters')
ValueError: names must be between 1-32 characters
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Teagan\Documents\Coding\Zupie\bot\classes\zupie.py", line 152, in main
await self.load_extension(extension)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\bot.py", line 869, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\Teagan\Documents\Coding\Zupie\env\lib\site-packages\discord\ext\commands\bot.py", line 794, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.code_snippets' raised an error: ValueError: names must be between 1-32 characters with this classpy
class CodeSnippets(
CogBase,
name="code snippets",
description="Cog that parses and sends code snippets to Discord.\nMatches each message against a regex and prints the contents of all matched snippets",
):```is it detecting the class description as being too long or something? because I don't think the name is longer than 32 chars
How is CogBase defined
Actually you can't have spaces in slash command names
Consider using a dash instead
You could but personally that’s not very intuitive
Okay, so I have this code to setup the MotorClient
async def main():
with open('./data.json', 'r') as file:
data = json.load(file)
async def hook():
bot.mongo_client = AsyncIOMotorClient(data['mongo_url'])
bot.setup_hook = hook
Currently, I'm calling that in other files by doing this
await main.bot.mongo_client['discordbot']['users'].find_one({"_id": payload.member.id})
There has to be a way I can simplify main.bot.mongo_client['discordbot']['users'], right?
I have to use it constantly
Oh yeah and I have import main at the top of each cog
Create a interface class. E.g ```py
class Database:
def init(self, client: AsyncIOMotorClient) -> None:
self.client = client
async def find_one(self, collection: str, document: str, **params: Any) -> Any:
return await self.client[collection][document].find_one(params)
So now you'd only need to do ```py
bot.mongo_client = Database(...)
```py
await bot.mongo.client.find_one("discordbot", "users", _id=12312)
would I put this in a class library file
Any is from typing.Any
^^^ or use an already made ORM
If there is an async ORM driver
most of the databases have a python orm for it, don't know about mongo though
would find_one(params) format it properly?
Like find_one({"_id": ctx.author.id})
Yes, I used ** making params take X kwargs. It will create a mapping of key-to-value pairs
!e ```py
def foo(**params: "Any") -> None:
print(params)
foo(_id=123)
@pliant gulch :white_check_mark: Your eval job has completed with return code 0.
{'_id': 123}
Oh cool, I'll learn about that soon
And if you only plan on using discordbot, you can set the default to it
So you'd only need to call ```py
await bot.mongo.client.find_one("users", _id=12312)
Okay, perfect
Thank you, I appreciate it
getting a circular import error
Because I have to import main.py into ClassLibrary.py so I can setup my User class (which uses the database), and I have to import the Database class into main.py because I need it to setup the MotorClient as a Database instance
@pliant gulch
The way you explained doesn't really make sense for me
async def main():
with open('./data.json', 'r') as file:
data = json.load(file)
async def hook():
bot.mongo_client = AsyncIOMotorClient(data['mongo_url'])
bot.setup_hook = hook
This is the main.py file?
Yeah, its in it
What do you guys like to put in the on_ready() event listener?
I personally like to do this: ```python
@commands.Cog.listener()
async def on_ready(self):
"""Code to be executed when the bot begins.
"""
print(f'\n{self.bot.user} is connected to the following guilds:')
for guild in self.bot.guilds:
print(f'- {guild.name} (id: {guild.id})')
And what are the affected imports?
so anywhere I want to use the bot.mongo_client, I have to use main.bot.mongo_client
so I have to import main into ClassLibrary where I setup my User class (which uses main.bot.mongo_client)
i do
async def on_connect(self) -> None:
print(
f"\nBot info:\nId: {self.user.id}\nName: {self.user.name}\nDiscriminator: #{self.user.discriminator}\nTag: {self.user.name}#{self.user.discriminator}\nGuild count: {len(self.guilds)}\nMember count: {len(self.users)}\nCog dir: {self.cogsdir}\nCreation date: {self.user.created_at}\nCommand count: {len(self.commands)}\n"
)
print("Bot has connected to the gateway")

And then I have to import the Database class from ClassLibrary into main so that I can use the Database class to create the bot.mongo_client thing
Can you show ClassLibrary
Ooo, I quite like that formatting 
i like printing all the info 
Yeah
from motor.motor_asyncio import AsyncIOMotorClient
import main
class Database:
def __init__(self, client: AsyncIOMotorClient) -> None:
self.client = client
async def find_one(self, collection: str, **params):
return await self.client['discordbot'][collection].find_one(params)
# This class will have methods to update the user's money, statuses, and id.
class User:
def __init__(self, user_id: int, name: str):
self.user_id = user_id
self.name = name
self.in_game = False
self.isBot = False
# Methods for checking user's current stats (like money, xp, status, etc.)
async def check_balance(self):
user_in_database = await main.bot.mongo_client.find_one("users", self.user_id)
return user_in_database["money"]```
How can I fix this error?
This is what I have in Class Library, so I need to import main into here so I can setup the User class, and I have to import Database into main so I can setup the bot.mongo_client = Database(...)
I think commands.Bot already comes with a tree
Just refactor your User class to take bot and then access by bot.mongo_client
would it be self.bot
Sure
How can I fix this error in the code?
Oh man now I'm getting runtime errors somehow
Initially I was thinking I could just make ```py
await main.bot.mongo_client['discordbot']['users']
So that I could just do
db = await main.bot.mongo_client['discordbot']['users']
db.find_one({"_id": 123})
Something like this wouldn't work because it's a coroutine object? @pliant gulch
I'm not sure why you'd do that though
is that on_ready supposed to be a command?
Just add the bot to the User's constructor method
How Do I Connect My Bot With MongoDB
No
Its just when bot runs it shows in the terminal that bots is ready for use
then why is it decorated as a command? probably where that error comes from
It's making things more complicated for me to understand
Then why is there a command decorator
Do I have to delete it?
No, it's just the wrong decorator
Ok
What decorator should I use
you don't have to, just use @bot.event -- the actual decorator you should be using
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
you could remove it, dpy already registers one when you create the Bot instance
you don't need to call event
Coro instead?
No, just don't call it
just leave bot.event, but without calling it
Ok
Without @ ?
with the @ since it's decorator, without the function call (() <- this part)
def in_game():
async def predicate(ctx):
try:
result = (await bot.mongo_client['discordbot']['users'].find_one({"_id": ctx.author.id}))["in_game"]
if result:
raise InGameError("Already in a game!")
return True
except TypeError:
await ctx.send("You might not be registered. Use **-register** to get started.")
return commands.check(predicate)
Help it doesn't know what bot is. How do I access bot if I can't do self.bot
ctx.bot
thanks
@pliant gulch Your stuff worked well, I just had to fix up some other stuff that was wrong. Also, you know how you did that **params thing for the find_one method? How would you do that for a method that had something like this:
await self.bot.mongo_client['discordbot']['users'].update_one({"_id": self.user_id}, {"$set": {"in_game": True}})
anyone?
okay uh. im new to python but i know the basics but could any one explain why this doesnt work?
i tried sending the embeds through a function but it seems to not work.
why isn't this working?
def MakeEmbeds():
embeds = discord.Embed(
title = "Kicked!"
)
await ctx.send(embed=MakeEmbeds())
await KickUSER.kick()
user.kick(reason=reason)
async def kick(ctx, user: discord.Member, *, reason="No reason provided"):```
does anyone know why my discord bot is not showing no error
Whenever i type the command it doesn't reply with anything
are you on v2.0
you gotta return the embed in the func
No, but isn't discord.py not ment to raise the errors
i do tho.
can i send my code
from Commands.database import dbcheck
class OTPCommands:
async def CheckPlan(ctx):
Plan = {
"MemberShip" : "",
"UserName" : id,
"Expiry Date" : ""
}
id = ctx.author.id
try:
id = (int(id))
if dbcheck(id) == True:
# Get Membership
GetPlan = dbcheck.PlanCheck(id)
if GetPlan == False: Plan['MemberShip'] = 'Error with loading Membership.'
else: Plan['MemberShip'] = GetPlan
#Get Expiry
GetExpiry = dbcheck.ExpiryCheck(id)
if GetExpiry == False: Plan['Expiry Date'] = 'Error with loading Expiry'
else: Plan['Expiry Date'] = GetExpiry
await ctx.send(f"Plan : {Plan['MemberShip']}\nUsername : {Plan['UserName']}\nExpiry Date : {Plan['Expiry Date']}")
except:
await ctx.send(" Sorry, but your user ID is invalid.")
soo
Of course it wouldn't raise errors you have a except
It's gonn send what you want
It doesn't send whatsa under except tho.
Does it even run
It does.
Then why are you expecting a error?
Becuase its not running
It is running
but when i type the command
its not returning anything
Wait is that a command?
yes.
on another file
@client.command("checkplan")
async def CheckUserPlan (ctx): await OTPCommands.CheckPlan(ctx)
So the function isn't working completely
Yes
Have you tried checking if any of the code is even getting called
Just by putting a print statement
Let me try.
Also you missed self
Alright so if i do 'print (" Start ! ")' before Plan = { it works, but after it, it wont
You don't always need self
Yeah i know looks weird to me though
Discord.py has always been weird, 1 for loop works second don't
Hold on
I see what could be a problem
In your plan
i did ID before it was called
Id is referrenced before it's assigned
oooooh i just realised
Alright thanks, it works but its weird that it wont raise the error
how would i call a function in another cog?
yessir
just call the coroutine?
await class_instance().method()
Thanks 😄

help me pls, i am not able to load jishakj extension on clinet like i used this client.load_extension('jishaku') btw error is coming client has no attribute load extension thoud before it i defined client as discord cljent and also set its command prefix
it doesnt seem their problem necessarily implies 2.0 since discord.Client doesn't have a load_extension method, only commands.Bot does
he said he used to be able to load extensions
well afaik load_extension was never a method of Client so my assumption is that they accidentally changed the class from Bot to Client
@bot.command()
@has_any_role('demand1', 'demand2')
async def demand(ctx, self):
guild = ctx.guild
demand1 = discord.utils.get(guild.roles, name="demand1")
demand2 = discord.utils.get(guild.roles, name="demand2")
self = ctx.author
await self.remove_roles(demand2)
await ctx.send("Demanded!")
if not demand2:
demand2 = await self.remove_role(demand1)
await ctx.send("Demands gone!")
``` im trying to make it where if demand2 is already gone but you use it again it removes demand1. My code isnt working, any help?
so you're trying to remove both?
so basically after they demand (remove) the first role from them then if they do it again the second
and you haven't handled the case if not demamd1
@bot.command()
@has_any_role('demand1', 'demand2')
async def demand(ctx, self):
guild = ctx.guild
self = ctx.author
demand1 = discord.utils.get(guild.roles, name="demand1")
demand2 = discord.utils.get(guild.roles, name="demand2")
if demand1 in self.roles and demand2 in self.roles:
# Remove the first one if the author has both roles
await self.remove_roles(demand1)
elif demand1 in self.roles:
# Remove the first one if the author only has the first role
await self.remove_roles(demand1)
elif demand2 in self.roles:
# Remove the second one if the author only has the second role
await self.remove_roles(demand2)
await ctx.send("Demands gone!")
something like that; i don't really get what you're asking though
its for a discord nfl league thing
can anyone tell me why this isn't working
im not too familiar with python operator since i just transition to python like a week ago.
what do you want to do with the colors argument
alanabeaton@sonic lintels-Air Avery Bot % /usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
/Users/alanabeaton/Avery Bot/main.py:24: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(ext)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
it's await bot.load_extension(ext)
you forgot the await
its to make it easier so for my Administration to make a embed message like
.embed Announcement Blah Blah blah blah Red
@left crater having another prob i imported discord.ui btw it is showing no module named discord.ui though i added import discord before it and installed it
How to fix that
ok ty!
Probably color=getattr(discord.Colour, colors.lower())()
and how will the bot differentiate i_title from i_descrpition
How to fix discord.ui import problem
Because it's not out yet
Try pip uninstall discord.py, and then doing pip install git+https://github.com/Rapptz/discord.py
Can i see the whole function
havent had issues with the script until I put it onto git
sure
if __name__ == '__main__':
for ext in extensions:
await bot.load_extension(ext)
bot.run('')```
hmmm
that im still thinking
assuming you are using discord.py v2.0, you should be using the async method setup_hook to do async setup for the bot.
yes that
how do I do that?
because I have never encountered issues with the script until now
the error is quite self explanatory
await can only be used within an asynchronous method
Then what should I tweak the code to be?
@dusky pine ok
Im importing cogs
override this method and do your logic in here.
@dusky pine its out i run it befoee it was working btw today im getting this error. Np i will try
nvm lol
yes but Im not sure what to do
Can i install discord py v2
heres my code:
from curses.panel import bottom_panel
from distutils import command
import discord
import os
from discord.ext import commands,tasks
from discord.ext.commands import has_permissions, CheckFailure
bot = commands.Bot(command_prefix='avery ', case_insensitive=True, help_command=None)
bot.remove_command('help')
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please type in the full command ** ')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements necessary to run this command :angry:**")
extensions = ['cogs.ModerationCog', 'cogs.CommandEvents', 'cogs.HelpCommandCog', 'cogs.UtilitiesCog', 'cogs.FunCog']
if __name__ == '__main__':
for ext in extensions:
bot.load_extension(ext)```
that does install the latest discord.py
what do u need help with?
@dusky pine yes btw how to install it i searched package manager btw its coming discord2
/Users/alanabeaton/Avery Bot/main.py:24: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(ext)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
/usr/local/bin/python3 "/Users/alanabeaton/Avery Bot/main.py"
yes
Ive never experienced this issue before
.
I tried that and it can only be used within an async function
...
can someone tell me what to do/tweak the code to?
subclass commands.Bot and override the setup_hook method
then you have an async method to do setup within (including loading cogs)
pip install git+https://github.com/Rapptz/discord.py
that's literally what i told you to do, the command installs the latest discord.py (v2)
straight from github
can you help me please. Im really stuck
class MyBot(commands.Bot):
async def setup_hook(self):
...
subclass commands.Bot, override setup_hook, load the cog there instead.
Ok! thank you
class MyBot(commands.Bot):
async def setup_hook(self):
...
if __name__ == '__main__':
for ext in extensions:
bot.load_extension(ext)```
@bitter perch
do I make the whole main.py a class?
you cant make a file a subclass?
and no
isnt the load extension method a coroutine hence the reason why you need setup_hook?
Okok
h
from curses.panel import bottom_panel
from distutils import command
import discord
import os
from discord.ext import commands,tasks
from discord.ext.commands import has_permissions, CheckFailure
class MyBot(commands.Bot):
async def setup_hook(self):
bot = commands.Bot(command_prefix='avery ', case_insensitive=True, help_command=None)
bot.remove_command('help')
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please type in the full command ** ')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements necessary to run this command :angry:**")
extensions = ['cogs.ModerationCog', 'cogs.CommandEvents', 'cogs.HelpCommandCog', 'cogs.UtilitiesCog', 'cogs.FunCog']
if __name__ == '__main__':
for ext in extensions:
bot.load_extension(ext)```
this is my code now but non of the cogs are loading
your using 2.0 right?
yes youre
^
just do what vaskel said lol
yes.. but Im saying I dont know how to do that 
this is my attempt
What to do to make it actually work after It updated to 2.0

^
Not working
you would need an init for the kwargs and you need to await the method and it should be done inside the coroutine with self as its a bot subclass and the if main should be outside of the class

Is it ok if you could tweak my code to work please because Im really stuck
from curses.panel import bottom_panel
from distutils import command
import discord
import os
from discord.ext import commands,tasks
from discord.ext.commands import has_permissions, CheckFailure
bot = commands.Bot(command_prefix='avery ', case_insensitive=True, help_command=None)
bot.remove_command('help')
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send('**Please type in the full command ** ')
if isinstance(error, commands.MissingPermissions):
await ctx.send("**You dont have all the requirements necessary to run this command :angry:**")
extensions = ['cogs.ModerationCog', 'cogs.CommandEvents', 'cogs.HelpCommandCog', 'cogs.UtilitiesCog', 'cogs.FunCog']
if __name__ == '__main__':
for ext in extensions:
bot.load_extension(ext)```
uhh well it will be quite hard for you as you would need to subclass the Bot class, may i ask do you know about subclassing and inheritance? if not i recommend you switch to disnake which they dont have the breaking asyncio changes
and better application commands implementation^
yes
wot is a CommandTree
i hate it
its confusing imo
the discord.py implementation is quite good.
may I ask how? In terms of organisation?
Im collaborating with someone and they are going to rewrite to disnake but Im trying to market something right now and they need to see the bot working and Ive received this error and its really embarrassing
and I have absolutely no idea how to fix it 
tbh to me its confusing as CommandTree doesnt really make sense
What should I do
talking about CommandTree
no I don't is it ok if you can please help me quickly rewrite it
commandtree is just the abstraction to hold slash commands

commands.Bot already registers its own tree
^
so you do not need a tree for your bot
yeah, but the way its been done just doesnt seem quite right to me
matches the rest of the library just fine
in general designing a sane slash commands implementation is quite literally impossible
(blame discord)
how?
Is it ok if someone could help me please Im really stuck I just need help making the main.py bot so I can show the marketers
^ I read the community announcement
they get messy fast and you have to follow discord's wants
Why are prefix commands being removed?
messy in the sense?
Whats the point
because discord hates bot devs
HELP LMAO
and loves forcing slash commands

!ban
its discord after all
^ can someone quickly fix this before we rewrite to disnake
anyone >>????????
to make both a good backend implementation while keeping the frontend ui to users is not an easy task
additionally, discord.py v2.0 also appeases type checkers
I WISH my collaborator was online but they arent and Im in a marketing meeting rn and its really embarrassing LMAO
because I literally dont know how to fix it
@sonic lintel my quite simple recommendation is that you read up on python and oop.
just send messages with their prefix
Im going to but I need it fixed asap can you please please please quickly fix it for me 
you cant
i can
not
but not sure how
bots literally cannot use the interactions api unless they're the one sending them
lmfao

help what
you trolling at this point
no
^
💀
i am serious guys
you quite literally can not
^
You can't
bro thats not what you said💀
I am new to the interaction api but I know that myself to and If I know that it says something because Im dead ass dumb
this guy is twisting his words now lmfao
i am not talking about normal discord bot token "i wanna use user token for doing that"
that's against discord's tos


