#discord-bots
1 messages · Page 517 of 1
Why turning into APK when you can install Python on a phone?
Official documentation for the discordbotlist.com API.
@slate swan Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
...
Just curious
it will work in top.gg also?
yea, this is a false positive, we have a PR up to fix this. The link they sent was https://docs.top.gg/libraries/python/
then what to do for top.gg?
i want to top.gg
not for discord bot list
Imagine if I want my friend to run my python bot on his phone as an app (so that the token will not get exposed)
Top.gg api
See link above
This one
saw that is for discord bot list
No they are two different sites they both will work differently ofc
That I tried to send but got flagged
No it's not.........
ohh ok
Yup
"""An event that is called whenever someone tests the webhook system for your bot on Top.gg."""
Read their docs
ok
Can someone tell how do I check how many servers my bot is in??
Get the length of the guilds attribute of your bot variable
len(list(bot.guilds))
Ty
Stop the 
?
Stop the spoonfeed
And bot.guilds already gives a list back, so doing list() is useless
Bro I didn't see your msg cuz you didn't ping me
!d discord.ext.commands.Bot.guilds
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
Chill Chill lol
oo
yes
i saw it was giving guild id with name and member count
so i thought it is a dict
:/
i didn''t saw [ brackets

:/
lol
if to edit a embed id someone react on it ?
client.wait_for
i want that that should never end
anytime the user can react
to change the embed :/
!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.
class discord.RawReactionActionEvent```
Represents the payload for a [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") or [`on_raw_reaction_remove()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_remove "discord.on_raw_reaction_remove") event.
Need help in #help-pancakes
Don't come to other channels to ask for help
You'll get help there we someone can help you
Hey seb
what takes the most RAM usage in dpy? Which cache?
Bruh

youre late 
no one answered anyway 
cz u asked Yea, sad
you ask now
Eh, I am going anyways
Cya then lol
cya
I'mma drive eat
please tell me if there is any method by which i can get date and time when server member joined discord
property created_at: datetime```
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
@spare lark
!rule 2
2. Follow the Discord Community Guidelines and Terms Of Service.
Selfbots are against Discord's ToS
Oh you mean safe? Like safe to use?
Selfbots are not safe to use, so discum isn't either
lol i was trying to make a music bot in python (how original) and got this error :(
ClientException: ffmpeg was not found
Have you even installed it
pip install ffmpeg?
yes
No lol
then how lol
ohh sorry misreas
This is just the library
ooh, thx
Do you even plan on using youtube_dl
!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)
You don't need to send the tag if they won't.............
i knew someone was gonna do the command when you said "youtube_dl"
ffmpeg can also be used to play mp3 that doens't use youtube
So pretty much irrelevant tag above
Could you now remove it to not flood the chat with an unnecessary tag @slate swan ? Thanks.
so if i make a music bot, ffmpeg or ytdl? or both possible?
Don't make a music bot that relies on YouTube
It's against their ToS and if your bot gets popular it will be forced to be shutdown like other bots.
And all your work will be wasted ¯_(ツ)_/¯
yea but none of my bots get popluar lol, so im not worried
Doesn't matter
Respect the ToS
And we won't help you any further about it anyways
im like the other thousands of ppl that dont even read the tos lmao
bro who even reads the yt tos? like 8 people
ik
Well the developer of music bot learned a lesson about that 😂
^^^^^^^^^^
definetly
but not me i still have music commands
ez lyf hack, dont publish ur bot to top.gg
its a private bot for me and my closest friends only
which will soon die at christmas cuz the code has gone uhh to complicated somethings i dont even know how i did it
youtube gets ddos attacks almost everyday, one or two undetected streams wont make a difference lol, but if your bot becomes popluar it is issue
Again
We don't provide help for that
Now feel free to make a music bot on your own
i alr have
Not you.....
thats what the docs are for
ohh
maybe i should sleep im starting to see things
does anyone know why the bots pfp is green (like its talking), when it joins a vc
Btw i heard that discord is making something like a music bot themself, so it is not even use to create it
"ive heard" 🤓
Heard from where?
🥴
Just like Discord is implementing games in voice channels
i hope they make an api thing where it charges ads from ur account and if u have premium idk, something
Hi
1st you have to bot.run(bot_token)
2nd you just revealed your bots token and now everyone can see and use it
This is not a valid bot token
Use the correct token
No?
so you tried eyy
No?
i knew someone would try
It's just common knowledge that a token is not that short
And doesn't have this type of structure
then how did you know?
No need to be Sherlock Holmes for that
And I believe this is a client secret
ive seen similar tokens like that
Random guess though
since i spam regenerate token quite alot
Bot tokens are not that small and don't look like that
ive seen similar
Client secrets
Those are not tokens
I can fully assure you tokens don't look like that
you cant know for sure until you try
I am sure though
what if your wrong?
I am not
Tokens have a STRUCTURE
That always look the same
And this token does not have it
No need to be Sherlock Holmes
i tried it worked
your wrong
bruh
jk lmao
if it was valid the Python bot would delete it
It's just not valid, as simple as that
i knooooow
It's eventually a client secret, but not a bot token
yes im sure everyone knows that
Not really no
it was sarcasm :|
bot token has three parts
is this true?https://www.youtube.com/watch?v=gNs5sCI1-dQ&t=52s
In this video, I talk about what happened to discord.py, why it got discontinued, and it's alternatives. I also showcase the Pycord alpha, which is a fork of discord.py that already has application commands.
If you have any suggestions for future videos/doubts, leave it in the comments below. I might not be able to answer everyone but you can j...
token has dots in between too
yes...
Discord.py isn’t broken yet you can continue to use it
i dont want to take risks tho
since its not supported anymore it wont have the new features that other apis have?
alternatives: none cuz all trash
then stick with dpy
but i what if discord announces like a cool new feature
then switch libs
nextcord? pycord?
oh yeaa
which are trash
I wouldn’t be worried about that I’d be more worried when they Introduce message intents
ive also been thinking abt intents
do i have to rewrite all my code that i spent like 2 weeks on?
aight
Message intents will only affect verified bots and not unverified bots if you didn't know that already.
Well, the way the permissions would work in the future of slash commands makes me want to move to slash commands either way
tbh i don't think an entire rewrite would be necessary, you'd probably just be enabling it the same way as with other privileged intents.
@client.command()
async def gcreate(ctx, time=None, *, prize=None):
if time == None:
return await ctx.reply("⌚ Please include a time!", delete_after=4)
elif prize == None:
return await ctx.reply("🏆 Please include a prize!", delete_after=4)
embed = discord.Embed(
color=discord.Color.blue(),
title="__New Giveaway!__\n\n",
description=f"\n\n**Hosted By:** {ctx.author.mention}\n**Prize:** {prize}"
)
time_convert = {"s":1, "m":60, "h":3600, "d":86400}
gawtime = int(time[0]) * time_convert[time[-1]]
embed.set_footer(text=f"Ends In: {time}")
gaw_msg = await ctx.send(embed=embed)
await gaw_msg.add_reaction("🎉")
await asyncio.sleep(gawtime)
new_gaw_msg = await ctx.channel.fetch_message(gaw_msg.id)
users = await new_gaw_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await ctx.send(f"**GG! {winner.mention} has won: `{prize}`**")
It is not showing the winner message...
Errors?
no.
What have you tried so far?
It is send the embed and I click the reaction, after like for example i set the time to 10s and I wait with no respond..
So you didn't tried to fix it by yourself, nothing new
Have you tried printing gawtime?
no...
hi
how to remove all reactions from a message?
!d discord.Message.clear_reactions
await clear_reactions()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes all the reactions from the message.
You need the [`manage_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission to use this.
ok
Why it is show me this?
Traceback (most recent call last):
File "main.py", line 1, in <module>
import discord
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/__init__.py", line 25, in <module>
from .client import Client
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 27, in <module>
import asyncio
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/__init__.py", line 21, in <module>
from .base_events import *
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/asyncio/base_events.py", line 296
future = tasks.async(future, loop=self)
^
SyntaxError: invalid syntax
Eh, the code is just import discord
Nothing else
update python
isn't that what I said Yea, probably that
What is the code for that?
There's no code
command*
Just install a Python exe from python.org bro
I have python 3.9
quick question - I am making bot for 1 specific server, how can I make a command such that it only works in 1 specific channel
No you don't
At least you don't use Python 3.9
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
hmm thanks
I have it
import discord
from discord import ext
from discord.ext import commands
token = ""
client = commands.Bot(command_prefix=">")
channel_id = client.get_channel(id)
@client.event
async def on_ready():
print("Script Started!")
print(client.user.name)
@client.event
async def on_message(message):
user_message = (message.content)
if user_message.lower == 'abc':
await discord.TextChannel.edit(channel_id, name = "test")
client.run(token)
anyone know how to change channel name?
That's now how it works
discord.TextChannel represents a channel object
And you shouldn't just copy paste that in your code as it will never work
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3.10/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3.10/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3.10/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
I need button code 🙃
what's the import to use get in channel = get(guild.channels, name = 'members')?
@hasty iron whats code for buttons
wdym?
thats a very vague question
instead of importing get just do discord.utils.get it makes your code make more sense imo
like discord.utils.get(guild.channels, name = 'members') ?
yep
Why it is never ends? @slate phoenix
no error
hey i am trying to make a command like prefix+suggest suggestion for dm of bot..if bot will get this so this message forward to owner for suggestions..how can i do can anyone help on this
get the owner id and then dm them the suggestion
I would suggest using command decorators instead of checking the content of every message
i mean if someone dm bot with that command so bot will forward that to me
yeah the bot can take that message and dm it to you
Will my bot get rate limited if i fetch the name, member count, owner, guild id, of all the servers my bot is in (89) i want it for statistical purposes and to remove bot from ghost servers
You’re only fetching the guild object but I would use bot.get_guild anyways
so im making an afk command, and when i use the command, it pings me(i ran the command), but while setting the embed thumbnail, it uses its own pfp. and i believe its setting its OWN afk, not mine. this is my code:
@commands.command()
async def afk(self, ctx, *, reason = "No Reason Provided"):
member = ctx.author
if member.id in afks.keys():
afks.pop(member.id)
else:
try:
await member.edit(name = f'[AFK]{member.display_name}')
except:
pass
afks[member.id] = reason
embed = discord.Embed(title = "AFK Set", description = f'{member.mention}, I set your AFK.', colour = member.colour)
embed.set_thumbnail(url = member.avatar_url)
embed.set_author(name = self.client.user.name, icon_url = self.client.user.avatar_url)
embed.add_field(name = 'AFK Note:', value = reason)
await ctx.send(embed = embed)```
im iterating through all the guilds my bot is in and putting guild.name and other info
I’d try using get_guild and if the bot is returning None then I would use fetch_guild but maybe sleep it per a guild just to be safe
hmmm
__Why it is never show the winner? __
No errors.
try to host giveaway for few seconds and ask 2-3 friends to participate if you're too low on members then remove users.pop(users.index(client.user)) then ur bot can also declare itself as winner, this statement only removes ur bot from giveaway. Make sure not to re-run the code as you're using asyncio.sleep() which is too bad and whenever ur bot is restarted then the code executing gets stopped and winner wont be declared
can anyone tell me how can i compare two permissions and decide by it which permission is greater i mean which has greater priviledges
what should I use instead of asyncio.sleep() ????????????
a database
and a task
store the time it began and the time it will end
keep adding to the time it began until it reaches the end time
then announce a winner
thats not python
oh
its c or c++
ye you are right
whats this about
nothing, giveaway is an intermediate command if you dont want to reset the value on restarting there are two things you can do
1)Code the giveaway command seperately and seperately host it so u can change other code and reboot other code but not the giveaway one. Its nto a good idea
2)This idea is much better use database and check it whenever bot is rebooted
can anyone tell me how can i compare two permissions and decide by it which permission is greater i mean which has greater priviledges
how do i get name of a role by giving the id?
i know java nicely but c langs just goes above my head soo badly
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
The name of the role.
imo java is similar to clangs
but C# is not that badly hard and quite similar to java
i think my java skills is now more than python lol
tmprole = ctx.get_role(role) ?
its a method of Guild
but does anyone know about what i sent before
not Context
?
damn
thats rpc right?
there is a python lib for it
!pypi pypresence iirc
is c# called c or cs or csharp
ctx.guild.get_role(role) could work?
yes if role is an id
yup
hm
one of these?
so this?
i wonder where i can find a big pip install pypresence hmmmm
hi, i want to make a check for a ticket system, so if someone already has a ticket open by the name for instance: ticket-rebellion that it would check if the channel exists, and if it does it won't let them open another ticket, but if it doesn't it'll open a ticket
i didnt saw this fr lmfao 💀💀
@hasty iron Pypi has a dark mode?
how to fetch the list of all persons connected to a voice channel
dk, i have dark reader extension on chrome installed
👍 🗿
How to create a stiky message?
im making an afk command, but when i use it, it says it set my afk, but then immediately removes it. this is my code:
@commands.command()
async def afk(self, ctx, *, reason = "No Reason Provided"):
member = ctx.message.author
if member.id in afks.keys():
afks.pop(member.id)
else:
try:
await member.edit(name = f'[AFK]{member.display_name}')
except:
pass
afks[member.id] = reason
embed = discord.Embed(title = "AFK Set", description = f'{member.mention}, I set your AFK.', colour = member.colour)
embed.set_thumbnail(url = member.avatar_url)
embed.set_author(name = self.client.user.name, icon_url = self.client.user.avatar_url)
embed.add_field(name = 'AFK Note:', value = reason)
await ctx.send(embed = embed)
@commands.Cog.listener()
async def on_message(self, message):
if message.author.id in afks.keys():
afks.pop(message.author.id)
try:
await message.author.edit(nick = remove(message.author.display_name))
except:
pass
embed = discord.Embed(title = f'Welcome back', description = f'Welcome Back, {message.author.name}! I removed your AFK')
await message.channel.send(embed = embed)
for id, reason in afks.items():
member = get(message.guild.members, id = id)
if(message.reference and member == (await message.channel.fetch_message(message.reference.message_id)).author) or member.id in message.raw_mentions:
embed = discord.Embed(title = 'Member AFK', description = f'{member.name} is currently AFK.\nAFK Note: {reason}')
await message.reply(embed = embed)```
Send a message, save it in a variable and then use .pin() on it
Anyone?
Iterate through all the channels and check for the channel name
??
tried that, but it didn't work
If done correctly it does work
Please help
last thing i tried was this if discord.utils.get(guild.channels, name=f"ticket-{interaction.author.name}") is None: but this didn't work either
!d discord.utils.get
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
Hello, can someone help me? I got this error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Member' object has no attribute 'server'
by trying to create reaction roles embed message. Can someone tell me what to do pls? Here is the code:```python
@client.command()
async def rr(ctx):
channel = client.get_channel(892014899587342356)
user = ctx.author
role = discord.utils.get(ctx.author.server.roles, name="✅ Verified")
em = discord.Embed(title='✅ Verify', color=discord.Color.green())
msg = await em.channel.send(embed=em)
await msg.add_reaction("✅")
await user.add_roles(user, role)```
In discord it’s called a guild not a server
Also just do ctx.guild
No need for the author in between
Can only cause more issues
okay, but how do i enter the exact channel
should i do guild = client.get_channel(892014899587342356)?
no, you should do myInt = "Hello World!"
print(myInt)
ofc
ah yes, guild.guild
can someone help me :p?
hey
if i hv the id of a message how do i get the message content? (dm channel)
!d discord.Message.content
The actual contents of the message.
no but i have to fetch the msg
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") from the destination.
is there any method by which i can get dash in command name like
$user-info
im wanting to make a verification command, how do i specify a role with a certain name?
you can get a role using discord.utils.get
role = discord.utils.get(guild.roles, name=rolename)
can u give me an example of how it would go in the code?
role = 'verified'
role_obj = discord.utils.get(guild.roles, name=role)
but where in the command?
right before the code where you assign the role to the user
@bot.command()
async def verify(ctx):
roles = []
for role in ctx.author.roles:
roles.append(str(role))
if "verified" in roles:
await ctx.send("You're already verified")
else:
role = discord.utils.get(guild.roles, name='verified')
await ctx.author.add_roles(role)
await ctx.send("You've been verified")
@fallow mauve
thx
hm
that's wrong lol
how do i import "guild"?
how
guild = ctx.guild
await
if "verified" in roles: not sure
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 28, in verify
for role in user.roles:
AttributeError: module 'discord.user' has no attribute 'roles'
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: AttributeError: module 'discord.user' has no attribute 'roles'```
my error
imagine not importing Guild
I couldn't do the thing I wanted to do 😔
replace it with
@bot.command()
async def verify(ctx):
roles = []
for role in ctx.author.roles:
roles.append(str(role))
if "verified" in roles:
await ctx.send("You're already verified")
else:
role = discord.utils.get(guild.roles, name='verified')
await ctx.author.add_roles(role)
await ctx.send("You've been verified")
user is your import
also you might have to change the if 'verified' in roles line
that still can be improved
discord.utils.get(member.roles, name='verified')
save that to a variable and check if its None
if its not, they're verified
else, add the role
yeah
"discord.guild has no attribute 'roles'"
since i dont think you need the user's role you can just do if discord.utils.get(member.roles, name='verified'):
im so lost
u need a map?
-_-
:)
might be helpful, idk
🗺️ here
yes, because you dont know basics
i do know basics
just never specified a role name before
wot
?
what does a role name have to do with an attribute error
huh, why does the discord.py library say guild.roles is an attribute
what
i didnt say that, i just dont know what im doing with this code bcs ive never done smth like it before, i wasnt talking about the error
i mean, didnt azrael spoonfeed you already
if thatd happened i wouldnt be having any problems, also i dont want spoonfed, i want to know why im getting these errors
lets start over
what things do i need to import for this to work?
ok
discord.py wont magically define a Guild object for you
if you dont know that then you definitely are missing some basics
code:
@Bot.command()
async def verify(ctx):
roles = []
for role in ctx.author.roles:
roles.append(str(role))
if "verified Member" in roles:
await ctx.send("You've been verified already.")
else:
role = discord.utils.get(guild.roles, name='verified Member')
await ctx.author.add_roles(role)
await ctx.send("You've been verified")
error:
Ignoring exception in command verify:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 35, in verify
role = discord.utils.get(guild.roles, name='verified')
AttributeError: module 'discord.guild' has no attribute 'roles'
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: AttributeError: module 'discord.guild' has no attribute 'roles'
yeah so guild is magically defined inside your function
define guild
the error is pretty simple and tells you what you should remove
!d discord.ext.commands.Context.guild
where guild
🧐
ded bot
lemme read the error again...
anyways you can use Context.guild to get a Guild object
ctx
?
very smart
which would make me cry
assuming the last two digits in his username are the last two digits in his birth year, he's doing pretty good for a 12 year old
12?
11 whatever
wow, getting farther and farther away
I've been awake for 15 hours, gimme a break
why do my commands still not work??
🗿
are you sure its 15?
I don't remember
lol
15 is a guess
ok
or commands.Context
pls help
innit
send your commands
you're missing something there
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html read the first example
i found it..
i give up for now, my brain hurts, i need to go eat smth
thanks
how do i fix this error TypeError: 'Int64' object is not subscriptable
my code
@commands.command()
async def buy(self,ctx,item_name,amount = 1):
data = loadf('databases/shop1.json')
item_name = item_name.lower()
name_ = None
for item in data["content"]:
print(data)
print(item)
name = item['id'].lower()
if name == item_name:
name_ = name
price = item['price']
buyer_money = user_balance.find_one({'_id': ctx.author.id})
buyer_cash = buyer_money['balance']['cash']
if price > buyer_cash['balance']['cash']:
await ctx.send('You Don\'t Even Have That Much Money Idiot 😛')
return
else:
user_balance.update_one(buyer_cash, {"$inc": {
'balance.cash': -price}})
user_inventory.insert_one({'_id': ctx.author.id, 'items': {
name_: amount
}})
await ctx.send(f'You have successfully bought {amount} {name_}')```
i have ```py
await c.send(f"{error[:2000]}")
```py
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/", line 939, in on_command_error
await c.send(f"{error[:2000]}")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1422, in send
data = await state.http.send_message(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 335, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 2000 or fewer in length.
member.roles. using ctx is ctx.author.roles
is there any fix to this
i figured out a simpler way, doesnt work as well but its better than trying to figure that way out while my brain hurts. i have no doubt ill be able to figure it out later but for now i need a break...
wdym?
await c.send(f"{error[:1986]}
wat?
? is it not self explanatory lol
Exactly 2k is obviously not working so make it lower.
error msg is probably just a bit misleading if sending exactly 2k chars isn't working
I want my discord bot to send a embed message every time I upload a video to YouTube, I want the embed message to have the link to the video. Where would I start to make this happen?
You should look into an API which does that.
That is, that API should fetch the yt notifs
And then the easy part connect it to ur bot and send as embed
I think I just found one it’s from google
please tell me how should i put - in command name like this
$user-info
@commands.command(name='anything_you-want')
i'm making command like this
@native granite
async def commandName(ctx):
how should i do in this
empty bot.command() sets command name to function name, you can specify name and there can be any symbols you want: py @bot.command(name='any-name') async def now_you_can_name_this_function_whatever_you_want(ctx):
okay
wdym?
Basically bot sends a message with thumbs up emoji. And I created a on_raw_reaction_add listener func, which reacts when somebody reacts with thumbs up
Is there a guide for Discord 2.0? I'm not really sure how I can do buttons that are interactive.
I'm using discord_components with Discord 2.0, but I've realized it comes in conflicts. What should I do?
whenever the bot sends a message with thumbs up, then the reaction_add func activates aswell
if you want to ignore all bots: if payload.member.bot: return, if only your bot: if payload.member == payload.member.guild.me
thanks man!!
on_raw_reaction_remove's payload shouldn't have member
it worked
I don't recommend you to use discord-components
there is all info in #guild-news in discord.gg/dpy
2.0 docs: https://discordpy.readthedocs.io/en/master/
2.0 examples: https://github.com/Rapptz/discord.py/tree/master/examples/views
welp it only worked on on_raw_reactoin add, not on on_raw_reaction_remove, which makes no sense
AttributeError: 'NoneType' object has no attribute 'bot'
it has)
Well, yeah, according to the documentations, it has to be the on_raw_reaction_add event for it to work
read the first line on member there
And the payload has to come from a guild
Represents the payload for a on_raw_reaction_add() or on_raw_reaction_remove() event.
member
what code do you have
mb
how do i work around this then
You can check if it's your own client by using paylod.user_id == self.client.id
thanks lads!
Thank you sir.
@tough wagon Also do you suggest using discord 2.0 or do you use something else for such things as buttons and slash?
You could use dislash but it’s unstable iirc
hmmm
It feels really weird to use 2.0, I was using discord_components all this time.
there's such documentation that really shows an example of creating buttons
I use nextcord which is a supported fork of discord.py and has buttons in it
I have not used them yet but there are some tutorial on youtube that shows to you how to use them
I saw that discord_components would conflict with discord.py which the buttons won't work on it. I thought I'd just stick to something simple for it.
Although, I'm not sure why people suggest using discord.py (2.0) for such a thing.
Somebody help I need to make a good impression on somebody and now it's not working
i'm not sure what could be the problem there because the edges are cut.
I'd assume you forgot to add ":" at the end of your if.
Nope... It's there
All of a sudden it's just broken
😭
it's not working?
It's STILL NOT WORKING
it says it's a syntax error
I'm so confused
what is it pointing at?
The :
I don't understand why it's invalid
Makes absolutely no sense
I'm going to restore another version that see if it'll work
It's fixed now-
I have no idea how
😔🔫
Can you send the code here next time possible? Screenshot wasn't the clearest
you could also do
if message.content == "whatever you write":
but I assume you want also characters after this
It's fixed now
what happened?
I think there was something wrong with python itself
There's no difference between the old version and the new one
hello how to mention a specific user in discord.py
!d discord.Member.mention
property mention: str```
Returns a string that allows you to mention the member.
where do I pass the user argument?
Is there a way to uninstall discord.py on pycharm? Because I seem to have some trouble out of it
whichever user/member you use the attribute on is gonna get mentioned
can you give an exemple please
File > Settings > Project Interpreter > Choose discord.py > Click '-'
member = ctx.author
await ctx.send(member.mention)
thnx if I want it to be a specific user I just set it to a variable?
You get (or fetch if member not present in cache) a member with it's ID
yes
and then you do yourMember.mention
Thanks
If i want to create a command which can be used both with slash or command prefix i had to declare the command twice or i can just do
@slash.slash()
@bot.command()
They're separate libraries
Twice iirc, ctx isn't compatible between the two
That sounds annoying 😂
For some reasons, I tried to use discord_components to prompt a button by using the command !button. However, for some reasons, the await client.wait_for() doesn't seem to work on Pycharm compared to Replit. Is there a reason why?
By the way, I used the same command for both of them. I don't know why is it only the one on Replit that works.
Welcome to the discord developer experience
And i can t even use discord.py embed into slash command i suppose, right?
Should be able to
async def button(ctx):
await ctx.send("This is a button",
components=[
Button(label="Nice!")]
)
interaction = await client.wait_for("button_click", check=lambda i: i.component.label)
await interaction.respond(content="Button Clicked.")```
I don't know how to convert it to python typo like everyone did
instead of ctx.author how can set the variable to a specific user I know it's a lot of dumb questions
for example you could use guild.get_member(id)
member = yourGuildInstance.get_member(396607194910556162)
would be u
make sure to have members intent enabled
and guild can be ctx.guild... ig?
You don't need members intent for that
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
async def ping(ctx):
guild=ctx.guild
sido=guild.get_member('439800066312503297')
await ctx.send(sido.mention)
cam you tell me what is wrong?
what do you want the command to do?
and is there any error?
ping sido
thnx it worked
How do we shortly delete the message after you do a command on python?
np
!d discord.ext.commands.Context.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
As you can see the send method has a delete_after
It takes an int has argument which is the time in seconds after the message should be deleted
Well then you have to you use ctx.message.delete
that's it?
It deletes the message that invoked the command
If you want to delete it after a certain time you have to use asyncio
does it take an argument when you do ctx.message.delete?
!d discord.Message.delete
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/master/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Oh so it had a delay lol, yes it takes delay which i think is the same as delete_after
thank you kind sir
!d discord.ext.commands.Bot.wait_for
wait_for(event, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.9)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.9)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.9)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/master/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
thats what ur gonna use
use the check to see if only that specific user votes
the thing i linked u also has examples
and?
They wont load, im new to using cogs so I have no clue what im doing
does it send any errors?
i have a try and except so it says cannot load
send the error
the full error
thats what it says
thats what i have it say
You have a custom error handler (try/except), remove it
ok then remove the try except and then send the full error
File "main.py", line 604, in <module>
bot.load_extension(extention)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: SyntaxError: invalid syntax (<fstring>, line 1)```
send the whole code in cogs.event
import discord
from discord.ext import commands
import datetime
from datetime import datetime
from replit import db
class Events(commands.Cog):
def __init__(self, bot):
self.now = datetime.now()
self.current = self.now.strftime("%H:%M:%S")
self.bot = bot
self.color = 0x2f3136
@commands.Cog.listener()
async def on_guild_join(self, guild):
db[f"{guild.id} welc"] = f"NEW GUILD"
db[f"{guild.id} msg"] = f"`SET NEW MESSAGE`"
db[f"{guild.id} footer"] = f"SET NEW FOOTER"
db[f"{guild.id} welcome"] = "ENABLED"
db[f"{guild.id} mod-logs"] = "CHANNEL.ID"
print(f"{self.current}: Joined new guild")
@commands.Cog.listener()
async def on_member_ban(self, member):
async for entry in member.guild.audit_logs(action=discord.AuditLogAction.ban):
embed = discord.Embed(title="Vira",description=f"""**Suspicious Activity**
Action: **Ban**
Author: **{0.user}**
Banned: **{0.target}**
""",color=self.color)
mod = db[f"{guild.id} mod-logs"]
await mod.send(embed=embed)
@commands.Cog.listener()
async def on_member_join(self, member):
t = db[f"{guild.id} welcome"]
if t == "ENABLED":
pass
else:
pass
def setup(bot):
bot.add_cog(Events(bot))
How can I fix this?
te = {
"🇦": "a",
"🇧": "b",
"🅱": "b",
"🇨": "c",
"🇩": "d",
"🇪": "e",
"🇫": "f",
"🇬": "g",
"🇭": "h",
"🇮": "i",
"🇯": "j",
"🇰": "k",
"🇱": "l",
"🇲": "m",
"🇳": "n",
"🇴": "o",
"🇵": "p",
"🇶": "q",
"🇷": "r",
"🇸": "s",
"🇹": "t",
"🇺": "u",
"🇻": "v",
"🇼": "w",
"🇽": "x",
"🇾": "y",
"🇿": "z"}```
Error: TypeError: can only concatenate str (not "dict") to str
uh, i dont see anything wrong
also, why are you importing datetime 2 times?
Please help me if anyone knows
Anyone know of a good lib which will allow me to proxy my bot as another bot? I saw d.py has some docs on it but I did some googling and found some slack and reddit threads saying that d.py's bot proxy system was broken due to a incompatibility with with aiohttp or something (it was a little while ago)
hi, im currently trying to fix some old code that is broken currently and it's a leaderboard command..
the code is here:
@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
users = await get_bank_data()
leader_board = {}
total = []
for user in users:
print(user)
name = int(user)
total_amount = users[user]["wallet"]
leader_board[total_amount] = name
total.append(total_amount)
total = sorted(total,reverse=True)
em = discord.Embed(title = f"Top {x} Richest People" , description = "This is decided on the basis of raw money in the bank and wallet",color = discord.Color(0xfa43ee))
index = 1
for amt in total:
id_ = leader_board[amt]
member = client.get_user(id_)
name = member.name
em.add_field(name = f"{index}. {name}" , value = f"{amt}", inline = False)
if index == x:
break
else:
index += 1
await ctx.send(embed = em)
and the error i get is discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: invalid literal for int() with base 10: "<member 'id' of 'User' objects>"
anyone know?
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.events' raised an error: SyntaxError: invalid syntax (<fstring>, line 1)
``` how do i fix
im guessing i unload it
what is amt?
id_ is a decimal so its raising that error
no fix??\
How about you fix your import statements and instead of using the datetime in the init you do it somewhere else
I honestly dont even know
??
the code is not mine, its some old code im trying to revive
why cant they use datetime in init?
original code here ~ https://github.com/AyushSehrawat/Economy-Bot
maybe that will help you
thats the problem, stop copying code and learn
make your own code
whats wrong with that?
im trying to lewaren
nothing wrong with it
just i dont have the skills, plus this seems easier
and ill get a basic idea of how it works
I think it'll be easier to just go datetime.now() and store that
If you just copy code from github you will not learning anything, you will finish up to don't understand nothing of what is written in the code
so your just doing that so thats its easier for u?
lol
i dont copy anything from github
fairs
somethings wrong with the first line in cogs.event
Helloooooooooooooooooo?
What is it?
why is there an emoji
Look at the website I posted
Everything on the left are emojis. You are able to copy and paste one of them onto discord. It turns into emojis.
i dont think this is related to #discord-bots ?
Okay, it's a bad word blocking part if my bot though.
to convert text to emojis if seen when swearing
And if you add bad words already in emojis where you're storing the text bad words
@bot.command()
async def idk(ctx, user: discord.User = None):
if user == None:
print("your hot")
profile = await user.profile()
mutual_guilds = profile.mutual_guilds
how would i use this to create an invite link to all the mutual guilds then print all of the invites in console
mutual guilds to who?
of*
why do you want to do that?
Are you selfbotting?
i wanna make my bot create an invite in all the mutual guilds then send them to me
no thats against tos
profile() is only allowed for Non userbots
and whatever yo're trying to do is called privacy breaching
You can just skip profile() and do User.mutual_guilds
!d discord.User.mutual_guilds
property mutual_guilds: List[Guild]```
The guilds that the user shares with the client.
Note
This will only return mutual guilds within the client’s internal cache.
New in version 1.7.
creating invites to random servers
How would I make an embed field without a name?
its not random
name="\u200b"
its invites to servers the user is in
import discord
from discord.ext import commands
import psutil
class Events(commands.Cog):
def __init__(self, bot):
self.now = datetime.now()
self.current = self.now.strftime("%H:%M:%S")
self.bot = bot
self.color = 0x2f3136
@commands.Cog.listener()
async def on_guild_join(self, guild):
db[f"{guild.id} welc"] = f"NEW GUILD"
db[f"{guild.id} msg"] = f"`SET NEW MESSAGE`"
db[f"{guild.id} footer"] = f"SET NEW FOOTER"
db[f"{guild.id} welcome"] = "ENABLED"
db[f"{guild.id} mod-logs"] = "CHANNEL.ID"
print(f"{self.current}: Joined new guild")
@commands.Cog.listener()
async def on_member_ban(self, member):
async for entry in member.guild.audit_logs(action=discord.AuditLogAction.ban):
embed = discord.Embed(title="Vira",description=f"""**Suspicious Activity**
Action: **Ban**
Author: **{0.user}**
Banned: **{0.target}**
""",color=self.color)
mod = db[f"{guild.id} mod-logs"]
await mod.send(embed=embed)
@commands.Cog.listener()
async def on_member_join(self, member):
t = db[f"{guild.id} welcome"]
if t == "ENABLED":
pass
else:
pass
def setup(bot):
bot.add_cog(Events(bot))
line 1: invalid syntax
its random to u isnt it?
Not really random
You have to indent after a :
The bot would need to be in the server as well
yes
to be a mutual guild
yeh
so back to the main question how can i use this to create an invite in all the mutual guilds
i mean, hes getting the guilds invites of the servers his bot and the user he mentioned has in common
Which makes it not a random server
The only thing to worry about is if you have permission from the servers owner if you can make invites
as discord has said before that they don't like that
yeh
im going to make it so the command only works if the server owner enables it
but anyways
thats besides the point
Sorry I pasted wrong
import discord
from discord.ext import commands
import psutil
class Events(commands.Cog):
"""Description here."""
def __init__(self, bot):
"""Initialize bot attributes."""
self.now = datetime.now(),
self.current = self.now.strftime("%H:%M:%S"),
self.bot = bot,
self.color = 0x2f3136
@commands.Cog.listener()
async def on_guild_join(self, guild):
"""Describe what this does.""""
db[f"{guild.id} welc"] = f"
Compare your begging code to this. You indented two spaces instead of four. You might want to fix your editor. You're not adding doc strings as well and they are pretty important.
btw you don't need the , after self.variable = value
what exactly are you talking about
liked in self.now = datetime.now(), you don't need the ,
ig he just wanted it, does not really change anything if he does not have that
ye
I think I fixed the whole indent thing
import discord
from discord.ext import commands
import psutil
class Events(commands.Cog):
"""Description here."""
def __init__(self, bot):
"""Initialize bot attributes."""
self.now = datetime.now(),
self.current = self.now.strftime("%H:%M:%S"),
self.bot = bot
@commands.Cog.listener()
async def on_guild_join(self, guild):
"""Describe what this does."""
db[f"{guild.id} welc"] = f"UILD"
db[f"{guild.id} msg"] = f"`SET NEW MESSAGE`"
db[f"{guild.id} footer"] = f"SET NEW FOOTE"
db[f"{guild.id} welcome"] = "ENABLED"
db[f"{guild.id} mod-logs"] = "CHANNEL.ID"
print(f"{self.current}: Joined new guild")
@commands.Cog.listener()
async def on_member_ban(self, member):
"""description"""
async for entry in member.guild.audit_logs(action=discord.AuditLogAction.ban):
ban_embed = discord.Embed(
title="Vira",
description=f"""
**Suspicious Activity**Action: **Ban**
Author: **{0.user}**
Banned: **{0.target}**
""",
color= 0x2f3136
)
mod = db[f"{guild.id} mod-logs"]
await mod.send(embed=ban_embed)
@commands.Cog.listener()
async def on_member_join(self, member):
"""Desc"""
t = db[f"{guild.id} welcome"]
if t == "ENABLED":
pass
else:
pass
def setup(bot):
bot.add_cog(Events(bot))
^
Hikari is one
I mean, the disgord library (go) is good but that’s not python lole
I can’t think of any other python ones to recommend
import discord
from discord.ext import commands
from replit import db
import datetime
from datetime import datetime
from discord_components import DiscordComponents, Button, ButtonStyle, Select, SelectOption
class Welcome(commands.Cog):
def __init__(self, bot):
color = 0x2f3136
now = datetime.now()
current = now.strftime("%H:%M:%S")
self.bot = bot
check = ""
@commands.command()
async def welchan(self, ctx, channel: discord.TextChannel):
j = db[f"{ctx.guild.id} welc"]
if channel is None:
await ctx.send(f"{ctx.author.mention} please mention a channel, or provide a channel name/id")
if j == "NEW GUILD":
del db[f"{ctx.guild.id} welc"]
db[f"{ctx.guild.id} welc"] = channel.id
embed = discord.Embed(title="Vira",description=f"""{self.check} Welcome Channel Set
Channel: **{channel.mention}**""")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Welcome(bot))
the cmd wont work, any idea why
why are you using replit db
Idk the format is fucked on mobile
thats not the issue
and that doesn’t answer my question
my question wasnt answered either
nope, the command just doesn't work
check is not an attribute
emoji id
??
ohh i get what your saying
ok, so why are you using replit db
how can I have a command like @client.command(), but have the bot respond to a word
as a command
but have you used it??
it’s practically json
it works tho right ??
Pretty sure at this point that repl.it's "database" is just a dictionary they made not ephemeral
checks out to me
how do i get the current time
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2021, 10, 5, 12, 1, 21, 352909)
I'm trying to pass a printed function from terminal to discord using my bot, how would this be done? at the moment I'm getting a message in discord that says function results at memory address
still very new to python
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.help' raised an error: TypeError: __init__() missing 1 required positional argument: 'func'
what does this mean
you aren’t passing an argument which you are supposed to pass to the init
Code?
im passing self, bot
And it looks like it needs another arg
got that bit working now, however discord doesn't seem to like ascii tables, so now trying to figure out how to pass the data from an sqlite query into embeds
import discord
from discord.ext import commands
class Help(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Command()
async def help(self, ctx):
embed = discord.Embed(title="Vira", color=0x2f3136)
embed.add_field(name=f"**Moderation**",value=f"`ban`, `kick`, `nuke`, `role`, `roleall`, `guildname`, `modlogs`")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/889013207849635843/892952355698540544/image0.png")
await ctx.send(embed=embed)
def setup(bot):
bot.add_cog(Help(bot))
fixed
the capital c in Command fuucked it uo
member intents exist
intents = discord.Intents.all()
in your bot constructor line
i got this after trying something new with my avatar command and adding a if statement
code?
@bot.command(aliases = ['av'])
async def avatar(ctx, *, member : discord.Member=Member):
if member == None:
member = ctx.author
emb=discord.Embed(title = f"{member.name}'s avatar", color = discord.Colour.random())
emb.set_image(url=member.avatar_url)
await ctx.send(embed=emb)
change the async def avatar(ctx, *, member : discord.Member=Member): to async def avatar(ctx, member : discord.Member=None):
why do u need * tho
idk why, i though i did for some reason
yeah its not necessary
anyways it work now
👍
this might seem like a dum question to ask but if i add a music bot to a server and someone reports it for idk breaking tos or smthn will the server be deleted or the bot
Just the bot I'd assume
Can't see why discord would delete the server over that
Why would a server be deleted if they are reporting?
But discord devs have been wonky in the past, so don't quote me on that.
im p sure youtube has to deal with that not discord and the server wouldnt be deleted
honestly discord wont bother removing small discord bots but your still breaking the tos
hey i mean its for 1 server lol
yes
becuz a mod is refraining to adding since he thinks its gonna delete the server if reported
dont want that 2 happen
the server wouldnt get deleted
for sure?
But at most youtube would send a c&d to the bots owner
they arent going for small bots though
what dym here
whats a c and d
cease and desist in short it means "piss off and we wont sue you"
lol
bet so i can heartfully add my bot in a 5000 member server without any effects to the server
the server will be fine
the bot may not be
but i doubt yt cares about a bot in 5000 servers
i really dont care abt the bot i can just make a new bot if it gets deleted for my own use with the same code different token
is on_guild_join valid?
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
yes
Not that simple I doubt you'd want to restart your bot after receiving letters from lawyers threatening to sue
i dont think my tiny bot will be sued
You know how labels are they are quite stingey I wouldn't be surprised
Not after groovy and rhythm shutdown
what about activity=discord.Watching?
its discord.ActivityType.watching
And clearly if your bot gets some action done to it such as being deleted I'm pretty sure eyes will be on you lol
and how can i get a full list of members? currently i have {len(bot.members)} but thats invalid
bot.users
so activity=discord.ActivityType.watching?
well if you're trying to change the presence its activity=discord.Activity(type=discord.ActivityType.watching)
after doing this it says my bot is watching 1 member, whilst being in a server with 80
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
weird, it showed how many servers it was in when i used bot.guilds
np
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('discord')
logger.setLevel(logging.INFO)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
```are there anything I can do to simplify this?
It's looking realllyy messy rn
is there a way to use requests to send an embed
omg what is this i've seen it everywhere
!d discord.User
!d discord.User
class discord.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
@lusty haven
what?
the embed you were looking for
oh ok
....
go into the docs for more abt it
how do i fix this error Command raised an exception: TypeError: 'Int64' object is not subscriptable
my code is ```py
@commands.command()
async def buy(self,ctx,item_name,amount = 1):
data = loadf('databases/shop1.json')
item_name = item_name.lower()
name_ = None
for item in data["content"]:
print(data)
print(item)
name = item['id'].lower()
if name == item_name:
name_ = name
price = item['price']
buyer_money = user_balance.find_one({'_id': ctx.author.id})
buyer_cash = buyer_money['balance']['cash']
if price > buyer_cash['balance']['cash']:
await ctx.send('You Don\'t Even Have That Much Money Idiot 😛')
return
else:
user_balance.update_one(buyer_cash, {"$inc": {
'balance.cash': -price}})
user_inventory.insert_one({'_id': ctx.author.id, 'items': {
name_: amount
}})
await ctx.send(f'You have successfully bought {amount} {name_}')```
What's loadf?
And in which line u getting the error?
def loadf(filename):
with open(filename, "r", encoding='utf-8') as f:
return load(f)```
Ah cool
umm price = item['price']
And what's printed when u print item?
load is json.load right?
Mhm
nothing
Seems like item is an int
{
"content": [
{
"id": "cookie",
"name": "Cookie",
"emoji": ":cookie:",
"price": 100,
"rarity": 1.0
},
{
"id": "apple",
"name": "Apple",
"emoji": ":apple:",
"price": 50,
"rarity": 1.0
},
{
"id": "banana",
"name": "Banana",
"emoji": ":banana:",
"price": 60,
"rarity": 0.5
}
]
}```
here is my shop json
this is correct right
Mhm
^
i really really wanna make my buy command work 🥺
.
They told...
oh sorry
Well, item is returning an integar instead of a list element
How to set 2 pics in an embed??
yeah you gotta do data["content"][item]["price"]
ye lemme try
Someone??
discord only lets you have 1
Why?
you can use the thumbnail as a second image though
This sucks
idk thats just how it is
Thanks for help
Command raised an exception: KeyError: 'content'
data[item]['price']
Works?
aren't they strings tho
i want it to check that its the using the correct part of the json
wdym
oh i see
yeah it should
if not, try enumerating the list like this ```py
for item_pos, item in enumerate(data['content']):
if item_name == data['content'][item_pos]['id'].lower():
Yea this should work
thanks guys it fixed it but there is another error
TypeError: 'Int64' object is not subscriptable
Which line
Guys
Is dank memer
Coded by
100s of people?
if price > buyer_cash['balance']['cash']:
No....?
im not trying to make a dank memer
no.
It wasn't directed towards you afaik
Whats the difference between guild.get_role() and discord.utils.get()
Seems like either buyer_cash or balance is an int
U can get using name also in the second one
hm
yes
Well, u gotta find out which one
U can also do utils.get(guild.roles, members=10) iirc
buyer money
python classes hurt my brain
Then just use that directly
wat abt the price
If they hurt your brain, don't see C classes then
?
owo
You gonna get a heart attack 😂
if price > buyer_cash['balance']['cash']:```
