#discord-bots
1 messages · Page 558 of 1
don`t working
i have send you frindship request please exept
there you can help me
is discord.py stopped?
what error
no
how to get animated avatar of user?? ctx.author.avatar_url returns non-animated
yes, it stopped development
oh ok
there are no errors, as well as the answer
are there any alternatives?
you can find someone else that'll accept helping in dms, also this is far from being discord bots related, ask in #python-discussion
oh ok ill see it thanks
yw
doobi doobi
@lusty swallow i fixed
it seems the same like discord.py tbh
@bot.command()
async def аватар(ctx, user:discord.Member = None):
if user == None:
user = ctx.author
userAvatar=user.avatar_url
embed=discord.Embed(title=f'{user.name} аватар',colour=0xffffff)
embed.set_image(url=userAvatar)
await ctx.send(embed=embed)
yeah it's same like dpy 2.0 only that it also has slashes and it's maintained and by far the best fork of dpy out there
please you can help me
i already told you, go to python.org and click download
hmm ok thanks it seems like a viable option
yw
i am telling in more things not only python
no i won't personally help you learn python, i ain't got time since it seems like you don't even know how to install python
does python 3.10 support disnake?
afaik yeah
what?
afaik = as far as i know
oh lmao
?? 😂
ah yes a software engineer who doesnt know the spelling of "software"
??
they deleted the message
pfft-
How to get the channel object using channel id
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
ok
@tasks.loop(seconds=600)
async def checker(self):
try:
fetchall = self.coll.find({}) # return all documents inside the db
print("Hello!")
current_time = datetime.utcnow()
async for x in fetchall:
if current_time >= x["BannedUntil"]: # do stuff after this
unbanuser = x["user_id"]
member = discord.Object(id={unbanuser})
guild = self.bot.get_guild(int)
await guild.unban(member, reason="Tempban for new account expired.")
await self.coll.delete_one(unbanuser)
except Exception as e:
print(e)
@checker.before_loop
async def before_checker(self):
await self.bot.wait_until_ready()
Thats a task in a cog to check against a db and unban however none of the prints are firing and its not working, I have that in my innit
are you sure you're loading the cog
Yes other commands in the cog work
try printing something at before_checker
before wait_until_ready and after, see if it starts and if it finishes
and a print above your fetchall
see if it prints then
kk
None printed no error either
weird
the code doesn't look like there's anything wrong 
Yeah been struggling for a long time now
then yeah idk how to help u sorry 😔
does the guild exisit?
is it the correct guild id
also you might wanna add a await client.wait_until_ready() above where you're getting the guild
since it's most likely not in the cache yet
so .get will return None
This basically ^^
Command raised an exception: ValueError: max() arg is an empty sequence
What is this error
your arg passed there is an empty iterable
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
How to make Enter on Embed description?
So i want make this for example in description embed
" test 1 tes 2 test 3"
to look like this
test 1
test 2
test 3
how i can do that?
Well its work, so how i can send code from description.
i want the code look like the original have a colour for example like this in description but have a colour.
HiresTextures = True
CacheHiresTextures = True
the code from .ini file, html, xml, & python
for example like this bot
here
what???
just put the string in Embed(description=””)
yes but it don't have a colour like the original code, its just white
wdym?
you need to use languages
like that
woah! its cool i will try that, thanks
@slate swan
yea?
how to use multiple prefixes
use a list
sure why not lol
i want to start discord.py , how to go ?
i can teach you how to make ur bot
I am absolutely newbie , so can you suggest me website where i can learn ?
newbie at what? Python or Discord.py?
nice. ill help u out one by one, dont go to tutorials they are bad
are you new to discord.py or python?
.py
okie , thanks 🥺
dont u have the announcements role tho...
https://vcokltfre.dev/ good alternative
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
in short , in both of them , because I know a small bit about python. Even not know the basics -_- , i just know some commands
?
then learn python first
okie thanks 🥺
nope , someone suggested me to go to this server and ask out
no i mean the @announcement role
okiee
u have it
ur indian
ok , lemme take
yeah , but why?
lol i knew it
your indian?
all indians talk the same 🤢
u realize
no 🤢
Yeah
^
Our native language is Hindi
ye that
glad to see , You know this -_-
!ban 548345298376720406 1m Xenophobic behaviour isn't tolerated here. Please follow our #code-of-conduct if you choose to join again.
:incoming_envelope: :ok_hand: applied ban to @tardy pasture until <t:1637836431:f> (30 days and 23 hours).
vc1 = await self.bot.get_channel(862915601332699137).connect(reconnect=True)
vc2 = await self.bot.get_channel(844178791735885824).connect(reconnect=True)
await vc1.guild.change_voice_state(channel=vc1, self_mute=False, self_deaf=True)
await vc2.guild.change_voice_state(channel=vc2, self_mute=False, self_deaf=True)
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/cogs/owner.py", line 1114, in on_connect
await vc1.guild.change_voice_state(channel=vc1, self_mute=False, self_deaf=True)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/guild.py", line 2943, in change_voice_state
channel_id = channel.id if channel else None
AttributeError: 'VoiceClient' object has no attribute 'id'
```help?
hi guys, please tell me how to ban everyone on the server using the command (all for educational purposes!)
Is it possible for a discord bot to know if you reply to a msg and get all text from that msg?
you're passing the VoiceClient to the channel parameter
ya
@client.command()
async def getkey(ctx):
with open('Whitelisted.txt', 'r') as fr:
if str(ctx.author.id) in fr.read():
await ctx.send("You already have a key check your messages with the bot!")
else:
with open('Whitelisted.txt', 'a') as f:
key = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(35)])
val = [
(f'{key}', f'{ctx.author.id}')
]
sql = "INSERT INTO beta_keys (key, discordid) VALUES (%s, %s)"
mycursor.execute(sql, val)
keydb.commit()
print(mycursor.rowcount, "was inserted.")
help?
with?
you can use the on_message event and check message.author and message.reference
???
👀 what sql database it that?
I would recommend learning python first instead of gluing code together.
ya i am doing the same thing to get bot guild and the channel
isnt it like the values supplied must be a tuple
That's for sqlite.
This looks like MySQL
no , since sqlites uses ? for values
they have %s so ill suppose its mysql
oh
@meager chasm?
vc1 must be defined as a channel , so dont use the .connect part if you want to use it in change_voice_state
Oh okay, and in that way I could get the text from the msg I reply to? For example I want a command that takes the text from a msg that I reply to
How to send bold letters inside code block
await self.bot.get_channel(862915601332699137).connect(reconnect=True)
await self.bot.get_channel(844178791735885824).connect(reconnect=True)
guild = self.bot.get_guild(746337818388987967)
vc1 = self.bot.get_channel(862915601332699137)
vc2 = self.bot.get_channel(844178791735885824)
await guild.change_voice_state(channel=vc1, self_mute=False, self_deaf=True)
await self.bot.server.change_voice_state(channel=vc2, self_mute=False, self_deaf=True)
```still not working
You can't
sad
error?
none
Once you get the MessageReference, you have access to the resolved attribute which can be the replied message
!d discord.MessageReference.resolved
The message that this reference resolved to. If this is None then the original message was not fetched either due to the Discord API not attempting to resolve it or it not being available at the time of creation. If the message was resolved at a prior point but has since been deleted then this will be of type DeletedReferencedMessage.
Currently, this is mainly the replied to message when a user replies to a message.
New in version 1.6.
does the bot gets completely disconnected?
you can
asd
no
I mean some text in bold and some in normal
can you show the complete code you have?
any if-else statements around
hm
How to make a cog.listener that send message to a specific channel when ctx.guild.member is online or offline?
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change:
• nickname
• roles
• pending...
could someone give me an example code on how I would edit a default help command?
I literally sent you the gist yesterday
There were examples
can you resend the link?
Converts all of the characters in a string to lowercase
I followed the tutorial but it wont work for me
import discord.ext.commands
from discord.ext.commands import Bot, Cog, Context, command
from discord import Colour, Embed
class MyHelp(discord.ext.commands.HelpCommand):
def get_command_signature(self, cmd):
return '%s%s %s' % (self.clean_prefix, cmd.qualified_name, cmd.signature)
async def send_bot_help(self, mapping):
embed = Embed(title="Help")
for cog, commands in mapping.items():
filtered = await self.filter_commands(commands, sort=True)
command_signatures = [self.get_command_signature(c) for c in filtered]
if command_signatures:
cog_name = getattr(cog, "qualified_name", "No Category")
embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
def setup(bot):
bot.help_command = MyHelp()
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'MyHelp' object has no attribute 'clean_prefix'
this tutorial isn't compatible with master version of d.py 😄
nothing works 😄
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
you want to set the "topic" setting to whatever you want it to display
while creating the channel you can use topic as optional arg
await server.create_text_channel(topic=") like this?
not just with this arg but is it like this?
eurm bro ! if i want to make the bot online 24/7 ,except replit and heroku, does there have any method ?
It's working thank you very much!
Sure
This
Does it free forever ? bcause heroku im already use 550 hours..
Ohhhhh i see ...
import keyboard
if keyboard.press == "p":
command = win.destroy
why doesn't work?
dpy channel
cool
use heroku -> make 2 accounts -> 1 goes off, turn on the other one

guys you know how to make a bot copy the author's message discord py
But after that the acc dies ,means i need to register one more??
Ouh okok. But after this time im still can use after while or need to open another ?
1 sec
@bot.command(pass_context=True)
async def (ctx, *,arg):
await ctx.channel.purge(limit=1)
await ctx.send(arg)
next month you can reuse it
Ohhhhhh like this . Thanks Bro .
-> pass_context is depreciated
-> Just use ctx.message.delete
-> Don't spoonfeed
hahaha okay
okay,thx
this is my first attempt at any help
-> it doesn't have function name
-> the code doesn't copy user's message
cool , but you should still not spoonfeed people , it doesnt help them to understand what they are actually doing
code: ```py
@avatar.error
async def avatar(ctx, error,*,arg):
if isinstance( error, discord.ext.commands.errors.MemberNotFound ):
msg = await ctx.send(embed = discord.Embed(title = '',description = f"{ctx.message.author.mention} Ошибка: Не существует такой юзер{arg}", color = 0x2f3136))
await asyncio.sleep(7)
await msg.delete()
await ctx.message.delete(
someone help?
,*,args are not required there
error functions need and use only commands.Context object and the error
so basically its just async def foo(ctx , error)
We already told you to not use an error handler as your command
mhm , its a really bad idea to use same function names for both command and error functions
there's no more arguments in an error handler
than ctx and error
Yes that too
But I guess they just wanted a say command, sooo 😐
Code: https://paste.ofcode.org/38jU6mGFi33A6szPzbKHHJR
why won't this work wtf, i'm trying to edit the default help command but this tutorial (https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96#list_page_source) is not even close to compatible with discord.py master version, how would I fix this?
!paste please use this to show your code, thanks
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I did?
The website...
doesn't matter what website it is
Well, sorry but I never heard of that website, sooo ain't opening it 😐
oh my god
don't respond then
Code: https://paste.ofcode.org/38jU6mGFi33A6szPzbKHHJR
why won't this work wtf, i'm trying to edit the default help command but this tutorial (https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96#list_page_source) is not even close to compatible with discord.py master version, how would I fix this?
nah. me neither

This code is 100% compatible with 2.0, you literally didnt do the last part
https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96#-integrating-classes-of-pagination
Lmao
Lol try running it with discord master branch, there is an error on every single line
i literally wrote that code, and it's working
what error did you even get
it's not working for me, what am I doing wrong then
I get almost "something" doesn't have an attribute called "something" on multiple lines
example
lmao
menu.current_page doesn't have an attribute called current_page
Ah, attribute errors suck
linter issue, has been since the first time menus was made
please actually show me the error, instead of talking about linter warning
self.helpcommand throws me a warning too and wont work
ok wait
Flake8 and Pylance always show all the possibile errors which can occur in each and every scenario, sooo I guess that's what u r getting?
first error is discord.ext.commands.errors.CommandNotFound: Command "help" is not found
and after im done with that, ill prob get 5-6 errors
U didn't call the brackets on bot.command()?
right, so you literally jump through the entire tutorial, didnt even read on how to add the helpcommand to your bot
i tried this bot.help_command = MyHelp() threw me a error on MyHelp()
i wont help you from here sorry, please read what i wrote
Nvm
this is the second error:
bot.help_command = HelpPageSource()
TypeError: __init__() missing 2 required positional arguments: 'data' and 'helpcommand'
and in your tutorial it doesn't show how to call this function
like i said, I did, it's this https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96#-integrating-classes-of-pagination
please, actually read what i said
yes I read the code?
you didnt
it's not even the same as mine
stop being stubborn, not once did i asked you to use HelpPageSource to bot.help_command, that's not even a HelpCommand class, that's the menu, that class you're suppose to use it in your help command class, which i wrote here ```py
import discord
from itertools import chain
from discord.ext import commands
class MyHelp(commands.MinimalHelpCommand):
def get_command_brief(self, command):
return command.short_doc or "Command is not documented."
async def send_bot_help(self, mapping):
all_commands = list(chain.from_iterable(mapping.values()))
formatter = HelpPageSource(all_commands, self)
menu = MyMenuPages(formatter, delete_message_after=True)
await menu.start(self.context)
bot = commands.Bot("uwu ", help_command=MyHelp())
i dont get why do you insist on everything i said
okay
commands.Bot("uwu "
lost my mind
you should've also included a "whole working code for help command"
I did, you pretty much ignored it
this is getting pointless i aint gonna argue
why is it so that when i view the invite page of my bot it shows 10 guilds and when i run len(bot.guilds) it shows 6 servers ? Which is more accurate and why
async def format_page(self, menu, entries):
page = menu.current_page
ok but why am i getting an error on this one?
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
menu.current_page has no attribute called current_page
Says it bro
it's supposed to have
new code: https://paste.ofcode.org/34nF8FXDCXMcp9YpwGRtXaj
still wont work:
bot.help_command = HelpPageSource()
TypeError: __init__() missing 2 required positional arguments: 'data' and 'helpcommand'
Are you sure you didnt misspelled it or something
yes
@slate swan When I get home I will try implementing the code but I do believe it was user error and not something wrong with the tutorial
hmm well when I check the tutorial, it's the same
and it should work

user error
you sure? check it
it's not a user error
How to get a server avatar using discord.py ?
!d discord.Guild.icon_url
pfft who uses 2.0
all the forks , and the @unkempt canyonbot is now synced with 2.0 iirc
pfffffft
class Newstuff(commands.Cog):
def __init__(self, bot):
self.bot = bot
class MyMenu(menus.Menu):
async def send_inital_message(self, ctx, channel):
return await channel.send(f"**Hello, {ctx.author}.**")
@menus.button('\N{THUMBS UP SIGN}')
async def on_thumbs_up(self, payload):
await self.message.edit(content=f'Thanks {self.ctx.author}!')
@menus.button('\N{THUMBS DOWN SIGN}')
async def on_thumbs_down(self, payload):
await self.message.edit(content=f"That's not nice {self.ctx.author}...")
@menus.button('\N{BLACK SQUARE FOR STOP}\ufe0f')
async def on_stop(self, payload):
self.stop()
@commands.command()
async def test(self, ctx):
await self.MyMenu().start(ctx)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NotImplementedError:
error ends here
I also have no idea what '\N{THUMBS UP SIGN}' should do, I just wanna test out the examples so that I can finally start
roles_mention = "\n".join(role.mention for role in ctx.guild.roles[:0:-1])
How can I get the roles.id from this?
same way
iterating through ctx.guild.roles
I thought that too
didn't work
what did you do
roles_id = [role.id for role in ctx.guild.roles[:0:-1]]
this returns a generator object innit
wdym
Generator object at 0xsomething
nah it must return roles ids for roles withing the [:0:-1] index
what error do you get?
it's a list comprehension, so it returns a list
nice
I'm gonna take my error to the dpy server
there are toxic professionals
if you server does not have any role , it will result into an error @slate swan
roles = sorted(ctx.guild.roles[:0:-1], key=lambda role: role.name)
roles_mention = "\n".join(role.mention for role in ctx.guild.roles[:0:-1])
roles_id = [role.id for role in ctx.guild.roles[:0:-1]]
# Build a list
role_list = []
for role in roles_mention:
role_list.append(f"`{roles_id}` - {roles_mention}\n")
how to make a bot count how many roles there are on the Discord
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds: Embed size exceeds maximum size of 6000
you embed size exceeds disocrd limit lol
LMAO
in a server , or all servers the bot is in?
in my server
roles = len(ctx.guild.roles)
you can use guild.roles and len
how can I solve this issue then?
^ the thing tokkarevv just sent
well , try to remove things you dont actually need in the embed
pagination
yeah , pagination is a better way to do it if you really need to send everything
# Sort the roles alphabetically and remove the @everyone role
roles = sorted(ctx.guild.roles[:0:-1], key=lambda role: role.name)
# Build a list
role_list = []
for role in roles:
role_list.append(f"`{role.id}` - {role.mention}\n")
this is what I did instead, but the roles are not sorted from highest rank to lowest
which is what im trying to do
according to your code , they are sorted according to name
its sorted alpha
yes
role.position is what you need
its like that because I don't know how to sort it from its position as high or low
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
or just dont sort it , it should already be sorted
mhm let me test that
Ah it works
im so dumb xD
why doesn't the bot write who is owner the server?
code:
emb.add_field(name="Owner", value=f"{ctx.guild.owner}", inline=True)
you need member intents for that
!intents
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.
or , you can mention them instead of their name using f"<@{guild.owner_id}>"
Btw, when I use role.position, the highest number is the higher rank, like I have 7 roles right, position 7 is the higher, but I want that to be printed as 1, basically reversed, so I tried doing reversed(role.position) but that doesn't work
you can just enumerate it
Thank you
it was a fricking typo
send_initial_message send_inital_message
example?
enumerate(role.position)
gives me incorrect type
wait, what are you trying to do?
role.position gives me the position of role (a specified role)
so if i check role.position on my owner role (which is the highest rank)
i get the position 7
since I have 7 roles, and its the higher one
but I want to reverse it, so the highest one is number 1, and the lowest one is number 7
How can I ignore discord.ext.commands.errors.CommandNotFound errors? Those errors are flooding my console D:
Found the solution on goold old stackoverflow
you can actually do it with math, so like
reversed_pos = abs(role.position - (len(roles) + 1))
stackoverflow > python server

@visual islandlol I tried doing role_pos = (role.position+1) - role.position it didn't work well, everything was 1 haha
yours doesn't work either
Worked for me
ah that's not what i'm doing, what I'm doing is this
embed.add_field(name="Position", value=role.position)
value = abs(role.position - (7 + 1)) then?
7 +1? it can vary on different guilds, that wont work
len(roles) + 1. That's why i gave the formula using len(guild.roles)
this?
That is another command
I can get len of a tuple right?
yup nah wont work
embed.add_field(name="Position", value=abs(role.position - (len(parsed_roles) + 1)))
Will this work?
@commands.group(invoke_without_command=True)
async def tag(self, ctx):
pass
@tag.command()
async def create(self, ctx):
await ctx.send("content")
what does it show?
sure
hm
hm?
i run it on my admin role (position 6) and i get position 4
does your code include @everyone role?
what does len(parsed_roles) return?
parsed_roles = set()
failed_roles = set()
all_roles = {role.id: role.name for role in ctx.guild.roles}
for role_name in roles:
if isinstance(role_name, Role):
# Role conversion has already succeeded
parsed_roles.add(role_name)
continue
match = rapidfuzz.process.extractOne(
role_name, all_roles, score_cutoff=80,
scorer=rapidfuzz.fuzz.ratio
)
if not match:
failed_roles.add(role_name)
continue
# `match` is s (role name, score, role id) tuple
role = ctx.guild.get_role(match[2])
parsed_roles.add(role)
and then I do ```py
for role in parsed_roles:
# etc....
embed.add_field(name="Position", value=abs(role.position - (len(parsed_roles) + 1)))
but that wont work
What do you wanna do?
I'm trying to reverse the role.position
If you want to list all the roles in a guild in reverse can't you just use reverse
Guys
Huh it's not documented?
I hosted my bot on heroku...and it is throwing errors on the image commands...which use the pillow libraries
Any suggestions?
I know that
Can't help without u telling the errors bro
another issue
bot_ping = (arrow.utcnow() - ctx.message.created_at).total_seconds() * 1000
if bot_ping <= 0:
bot_ping = "Your clock is out of sync, could not calculate ping."
else:
bot_ping = f"{bot_ping:.{ROUND_LATENCY}f} ms"
# Discord Protocol latency return value is in seconds, must be multiplied by 1000 to get milliseconds
discord_ping = f"{self.bot.latency * 1000:.{ROUND_LATENCY}f} ms"
``` I'm trying to get my bots ping, but it always returns the first if statement
np
Hey guys, I am making a public discord bot and i wanna make my bot know what servers the owner of the server is in, how do i do that?
Why don't you do that to round? round(bot.latency*1000,1)
huh
isnt the bot ping normally > 0
makes sense why it did that didn't it
oh hm
There is a issue and idk what the issue is tbh
could be arrow that's not working properly
self.bot.latency * 1000 returns the API latency in ms and that one works fine, bot_ping is the issue
ah ok
hello i am new to pyton
what the
Guys this is not setting the image
embed.set_image(url="attachment://wl.png")
bot_ping = (arrow.utcnow() - ctx.message.created_at).total_seconds() * 1000
if bot_ping <= 0:
bot_ping = "Your clock is out of sync, could not calculate ping."
else:
bot_ping = f"{bot_ping:.{ROUND_LATENCY}f} ms"
# Discord Protocol latency return value is in seconds, must be multiplied by 1000 to get milliseconds
discord_ping = f"{self.bot.latency * 1000:.{ROUND_LATENCY}f} ms"
``` I'm trying to get my bots ping, but it always returns the first if statement
How do you guys make your bot add a reaction to a message then it will check if a user reacted to it? I use this to make the bot react with ⚔️ to the embeded message, and it does it greatly, but when the player adds a similar reaction it doesn't get detected and I can add a different ⚔️ and the other one gets detected.
sweet! I didn't know that it could be done!
Channel is a rucuss
discord on top
Url has to start with https or http
Print bot_ping
!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**...
add it with an str form of the emoji
but.....an api uses the same method ;-;
and it works for them
What?
!d discord.File
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
^
I want it to be an embed
"⚔️"
-4157.0070000000005
👀 thats how sending a local image works , aint sure if they are doing it
await message.add_reaction("⚔️")
full code pls
mhm
What's arrow.utcnow()
!pypi arrow
Well, you can't. discord.Embed.set_image doesn't take a file parameter, only a URL.
@client.event
async def on_member_join(member):
with open("configure.json", "r") as f:
channels = json.load(f)
members = int(member.guild.member_count)
try:
channel = channels[str(member.guild.id)]["welcome"]
welcomeChannel = client.get_channel(int(channel))
embed = discord.Embed(title=f"Welcome {member.name}! Member: {members+1}", color=member.color)
wanted = Image.open("images/border.png")
asset = member.avatar_url_as(size = 128)
data = BytesIO(await asset.read())
pfp = Image.open(data)
pfp2 = pfp.resize((1050, 650))
wanted.paste(pfp2, (90, 50))
wanted.save("wl.png")
embed.set_image(url="attachment://wl.png")
await welcomeChannel.send(content=None, embed=embed)
except:
pass
its because you are sending the embed but not the file py embed = discord.Embed() embed.set_image( url="attachment://filename.png" ) image = discord.File("/path/to/filename.png") await ctx.send( embed=embed, file=image ) this is how sending local images work
but the image will be outside the embed
it wont be ...
waitup ill get an example
ah okay...i'll try
Ok what does arrow.utcnow() and ctx.message.created_at return
Probably the same time
arrow.utcnow(): 2021-10-25T14:38:39.560139+00:00
msg.createdAt: 2021-10-25 14:38:43.723000+00:00
thank you!! it worked
There
So how can I solve this issue?
It's the same time so either it's gonna return in negatives or only 0
oh cool , sorry it was taking too much time to send an example because i forgot some paths lol
its not, its 38:39 and 38:43
Wait
🫂 Don't be sorry
@slate swan i tried it and it sent me a positive int result
idk why thats happening to u
also i used datetime
someone said it might be my system datetime being out of sync
idk tbh, maybe try with datetime instead of arrow
because the message got created in the future
2021-10-25T14:47:41.558235+00:00 2021-10-25 14:47:45.615000+00:00
that T after the date, whats that
i have no clue
probably time zone
idk, how could I use datetime instead of arrow in this case
just import datetime and then do datetime.datetime.utcnow() instead of arrow.utcnow()
whats the difference in utcnow() and now()
my bots in a server and i want to create a invite of that particular server (ik the id) how can i do that
utc timezone and the now() does not have utctimezone
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can't subtract offset-naive and offset-aware datetimes
Question:
I want to make a bot that stores an individual variable for each person that uses it, for example, storing points, they use, say ?balance and there is a variable stored for them, and it responds with like 1000 and somebody else says the same command but they have their own variable and the bot responds, say, 1
how do i change my bot's activity
um
you have to use databases
wth is database
!d discord.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
!d discord.Client.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Example
```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
``` Changed in version 2.0: Removed the `afk` keyword-only parameter.
A database is an organized collection of structured information, or data, typically stored electronically in a computer system. ... The data can then be easily accessed, managed, modified, updated, controlled, and organized. Most databases use structured query language (SQL) for writing and querying data.
google "what is a database"
how would I fix this lmao
send what u have atm
bot_ping = (datetime.datetime.utcnow() - ctx.message.created_at).total_seconds() * 1000
and how did you import datetime
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can't subtract offset-naive and offset-aware datetimes
import datetime
ok
try with .now()
instead of utcnow()
same thing happens, already did
then its probably this
how is that possible
ok thx
My timezone is CEST, 2021-10-25 16:55
its seems pretty limited
haha, if you think of storing those information in a file and access them like a variable, you'd have to use json or something similar, and it will eat up your space in your system
yay
yay?
ok
json as a db?
and its corrupt
my bots in a server and i want to create a invite of that particular server (ik the id) how can i do that
lol no
nah i was being sarcastic
lol
why do you want to do that
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
Get a channel from that server and create an invite for it.
Though, you cannot create an invite for the guild itself.
oh okay
can u help me, ik u have a lot of experience
bot_ping = (datetime.datetime.now() - ctx.message.created_at).total_seconds() * 1000
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can't subtract offset-naive and offset-aware datetimes
we think the issue might be because of my system datetime being out of sync, but how can I fix that?
!d discord.ext.commands.Bot.latency
property latency: float```
Measures latency between a HEARTBEAT and a HEARTBEAT\_ACK in seconds.
This could be referred to as the Discord WebSocket protocol latency.
not what I'm trying to do
Try datetime.utcnow() - ctx.message.created_at.
how can i remove roles from User object, not Member, I used bot.get_user(id) to fetch a user but didn't know how to remove a role from them
u cant create invites with an integer
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
user.remove_roles()
literally the same syntax
You can't manage a User object's roles.
i get the same error
whats the diff between member/user class
ok tks
Member is a member inside a guild and User is a Discord user.
umm i just did that
There's a big difference.
oh thanks
i fetched a random channel and made an invite of it
oops I thought you meant using the guild id
yeah i did use the guild id
what
@client.command()
async def guildinv(ctx):
guild = client.get_guild(830316313808470057)
channel = guild.channels[1]
invitelink = await channel.create_invite(max_uses=1)
await ctx.author.send(invitelink)```
thats channel
cool
Fyi, to get the first item in an array you have to use index 0 and not 1. Index starts from 0.
i dont see a reason for it to not work , just your code copy pasted
huh
isnt the syntax for .channels like this?
category:
channel
``` i think he was doing this
!e
array = ["first item", "second item"]
print(array[0])
print(array[1])
@dapper cobalt :white_check_mark: Your eval job has completed with return code 0.
001 | first item
002 | second item
i know
just saying .channels
returns the categories too
Y'all clearly never used dpy 2.0
Dpy 2.0's .created_at returns a timezone aware datetime
so , does created_at not return a datetime object now?
!d discord.Guild.text_channels
property text_channels: List[discord.channel.TextChannel]```
A list of text channels that belongs to this guild.
This is sorted by the position and are in UI order from top to bottom.
oh
It does but it not naive anymore
makes more sense , its now an offset-aware datetime as per the error
And since it's a datetime object you can use .replace(tzinfo=None) to make it naive again
@slate swan add this at your .created_at
I got it working
time_1 = time.perf_counter()
await ctx.trigger_typing()
time_2 = time.perf_counter()
bot_ping = (time_2-time_1)*1000
¯\_(ツ)_/¯
why when i do this the command does not send
r = requests.get("https://nekos.life/api/v2/img/kill")
res = r.json()
embed = discord.Embed(color=0x2f3136,
timestamp=datetime.datetime.utcnow(),
description=f"{ctx.author.mention} killed {user.mention}",
)```
Well, you're not sending it anywhere
Also don't use requests, it's blocking
the , after description = "..... may be painful
Why?
when i use hug it works :/
its not that
use aiohttp for an async enviroment
As i said, you're not sending the message
i didn't just say that this too ^
because it has no kwargs after that?
see
Yeah but it didn't really make a difference
You're not sending the message
did u send the message
it for sure raises an syntax error
It doesn't
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
hi
huh?
Bruh
!e
def a(b, c, d,):
return b
print(a(1, 2, 3))
@boreal ravine :white_check_mark: Your eval job has completed with return code 0.
1
still works easy
why hug works but not kill ??
show the full command
Yeah and it won't magically send your message if you're not sending it wtf
k
✨ god ✨
@commands.command()
async def kill(self, ctx, user: discord.Member = None):
if user is None:
await ctx.send(f"`{ctx.author}` you must mention a user to do that!")
else:
r = requests.get("https://nekos.life/api/v2/img/kill")
res = r.json()
embed = discord.Embed(color=0x2f3136,
timestamp=datetime.datetime.utcnow(),
description=f"{ctx.author.mention} killed {user.mention}",
)
embed.set_image(url=res['url'])
embed.set_footer(text=f"{ctx.guild.name}")
await ctx.send(embed=embed)```
oh thank goodness there is a dedicated channel for this, I want to make a discord bot that does a couple of hopefully simple things for a game server I am running. It needs to download files from a file server, then execute a command in the game's cmd and write to a cfg file which is just a text file. Never done anything with python before and I want to get this up soon not in 4-6 months after I learn python "real quick"
is there another way to go about making a discord bot
By learning python
What you want to do requires quite some knowledge
By learning discord botting with a programming language you already know.
And no one's gonna baby sit you until you learn python
never done any programming before :/
@boreal ravine
Nor gonna spoonfeed/give you already made code
ok
Then it's a good time to start learning and doing some smaller projects before
Add prints everywhere and see if they work
Where can I find what does ctx is in the docs?
is datetime defined?
icon_url kwarg
!d discord.ext.commands.Context
class discord.ext.commands.Context(*, message, bot, view, args=..., kwargs=..., prefix=None, command=None, invoked_with=None, invoked_parents=..., invoked_subcommand=None, ...)```
Represents the context in which a command is being invoked under.
This class contains a lot of meta data to help you understand more about the invocation context. This class is not created manually and is instead passed around to commands as the first parameter.
This class implements the [`Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") ABC.
uh where exactly in the footer?
embed.set_footer(text="bot made by gorgonzola#6770")
It's a kwarg so it doesn't matter where
ok
you can't in the footer (u can but its small af) but you can in the embed by using .set_image(), .set_thumbnail (more ways but the image is small)
i already saw it in footer many times tho huh
how big was it
yes
it works just when i put killed at
https://nekos.life/api/v2/img/kill```
it would not work
any errors?
@client.command(name="help")
async def helpDef(ctx):
embed=discord.Embed(title="SCS Search Bot Commands", description="doenst matter",color=0xffffff)
embed.set_thumbnail(url="doesnt matter")
embed.add_field(name=":scroll: Commands:", value="doesnt matter", inline=True)
embed.set_footer(text="bot made by gorgonzola#6770")
await ctx.send(embed=embed)
``` why do i get ```Traceback (most recent call last):
File "main.py", line 42, in <module>
async def helpDef(ctx):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1263, in decorator
self.add_command(result)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1149, in add_command
raise CommandRegistrationError(command.name)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.```
Because there's already a built-in help command
no
KeyError: "url"
client.remove_command('help') right below where you define client
try hug
this the link doesnt exist @lyric moat
ok ty :)
yeah
what could i put instead of kill?
idk?
any1 who can send me a example code on how to use on_command_error?
Which ones better to use, mongodb or SQLite?
does anyone know how to use the read messages scope on apps
async def on_command_error(ctx, error):
if isinstance(error, commands.THE_ERROR_TYPE):
#error message
depends on your bot
What does that means
ty
idk if u sqlite better but harder but mongo easier
Why is the error that there is no argument displayed to me in the command line, and not in the chat?
Wym...?
What?
Oh, thanks you
I'm trying to get a list of reactions on a post and then loop through them to delete them if they are in a list of mine.
if str(payload.emoji) in letters:
print ('yea')
uprint(msg.reactions)```
!src docs
Look up documentation for Python symbols.
?
#bot-commands is there bro
cap
Okay....?
No cap
okay...?
I mean, what's the problem?
Ah
i'm staring at the discord docs for reactions. I can't seem to figure out
only attributes for class discord.Reaction are count,customer_emoji,emoji,me,message
!d discord.RawReactionActionEvent
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.
!d discord.RawReactionActionEvent.message
No documentation found for the requested symbol.
Breh
not exactly what i am looking for
I am trying to get list of reactions on a message. then loop through them and delete ones in the list
Has someone checked this?
Please help me
message has been fetched
!d discord.PartialMessage.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.
not trying to clear reactions, those clear all reactions
Ah no need to fetch
i'm only trying to delete certain ones
!d discord.TextChannel.get_partial_message
get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.
This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
Use this, don't fetch the message. Save an API Call
!d discord.PartialMessage.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.
There, use this
not what i'm looking for I don't think
!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.
this doesn't give me a list of them that I can loop through and delete
?
Bruh payload.emojis returns the emoji, check if the emoji.name is in the list and if it is, then just delete it after getting the partial message
no
Format your code. Read the embed
that's not what i'm looking for
Then?
i can do that easily
okay again
I'm looking to get a list of reactions on a post... then loop through them and IF they're in a list delete them
not as they're being added
!d discord.Message.reactions
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
And loop
Okay, so
And check
I was fast
!d discord.Member.roles yes
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
That wasn't my problem. I was just inquiring how to edit a certain area of embed
thanks
!d discord.Message.embeds returns the list of discord.Embed objects
A list of embeds the message has.
But there is no guide on how to edit embeds.
You just do
embed = message.embeds[0]
embed.description = "I edited an embed!!!"
await message.edit(embed=embed)
with python await msg.remove_reaction(payload.emoji, payload.member)
using just msg.reactions I cannot get member
!d discord.Reaction
class discord.Reaction```
Represents a reaction to a message.
Depending on the way this object was created, some of the attributes can have a value of `None`.
x == y Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.
x != y Checks if two reactions are not equal.
hash(x) Returns the reaction’s hash.
str(x) Returns the string form of the reaction’s emoji.
Eh, lemme see
await remove(user)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove the reaction by the provided [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") from the message.
If the reaction is not your own (i.e. `user` 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 `user` parameter must represent a user or member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
If the user sent this reaction.
There
@client.command(name="wallpapers") how can i have a 2nd possibility like || in js
U mean aliases?
yes
Just do (name="", aliases=[list of strings])
so i use msg.reactions to get the list then loop through the list and use reaction.me?
uh alright
reaction.me returns the user who added the reaction
Do you not have a RawReactionActionEvent object? Since you named it payload I am assuming you are using one of the raw reaction events
@bot.event
async def on_message(ctx, message, member: discord.Member):
if '@worn fern' in message.content:
await ctx.send('test')
and error :
https://cdn.discordapp.com/attachments/741041275188281454/902217341536981162/unknown.png
and what if I want to edit only one field of the embed?
!d discord.Embed.fields
property fields: List[_EmbedFieldProxy]```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of `EmbedProxy` denoting the field contents.
See [`add_field()`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.add_field "discord.Embed.add_field") for possible values you can access.
If the attribute has no value then [`Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty") is returned.
U have only message param in on_message
okay so I get the list. loop through and use reaction.me to do what?
wdym
U can loop through them and if they are in the list, then reaction.remove(reaction.me) keeping in mind the API Calls this is gonna make
@bot.event
async def on_message(message):
. . . .
@client.command(name="", aliases =["wallpaper", "wallpapers"]) like that right
Yups
I am literally helping 3-4 people at one time lmao
Ok then, you mean I should enter some number here, and while editing, I should be doing edit.embed[*that number*]
That means it's a kwarg
!kwarg-arg
Correctly written function to remove all roles?
!positional-keywords
Positional vs. Keyword arguments
Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.
Example
>>> print('Hello', 'world!', sep=', ')
Hello, world!
The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.
Note
A keyword argument can be passed positionally in some cases.
def sum(a, b=1):
return a + b
sum(1, b=5)
sum(1, 5) # same as above
Somtimes this is forced, in the case of the pow() function.
The reverse is also true:
>>> def foo(a, b):
... print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
More info
• Keyword only arguments
• Positional only arguments
• !tags param-arg (Parameters vs. Arguments)
There
!d discord.Member.remove_roles
await remove_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.
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 removed [`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.
like this?
for x in msg.reactions:
if x.emoji in letters:
await reaction.remove(x.me)```
@bot.event
async def on_message(message):
if ('@worn fern') in message.content:
await message.channel.send('test')
like this?
Yups
Yups
NameError: name 'reaction' is not defined```
Ah, it should be x.remove
oh yes
My bad, sorry
my bad!
again it doesnt responding
Thanks so much for the help and fast responses
Remove the () from the string
It's fine haha. Happy to help
again nothing
New code
@bot.event
async def on_message(message):
if '@worn fern' in message.content:
await message.channel.send('test')
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
!d discord.Message.raw_mentions
A property that returns an array of user IDs matched with the syntax of <@user_id> in the message content.
This allows you to receive the user IDs of mentioned users even in a private message context.
I did so, but still does not take off the role
Use the second one
okay
@maiden fablebtw this is for when i tag the bot then the bot send a text
@client.command(name="", aliases =["best cube", "best yter"]) how can I use a space character in my command name?
!d discord.ClientUser.mentioned_in
mentioned_in(message)```
Checks if the user is mentioned in the specified message.
just use if bot.user.mentioned_in(message)
File "C:\Program Files\Python39\lib\site-packages\discord\reaction.py", line 122, in remove
await self.message.remove_reaction(self.emoji, user)
File "C:\Program Files\Python39\lib\site-packages\discord\message.py", line 1259, in remove_reaction
if member.id == self._state.self_id:
AttributeError: 'bool' object has no attribute 'id'```
wait, why do u have name like that lol
any idea what this is talking about
Urghhhh gimme code please. the whole part of the command/event
wait uh you told me to when using aliases
what should it be
ah no. It was just an example haha
oh
for x in msg.reactions:
if str(x.emoji) in letters:
await x.remove(x.me)```
what is it supposed to be? and do you know how i can have these space characters?
try printing every variable. x, x.me, x.emoji
sure. just set the name kwarg to the name u want to set of the command
It works thankss
Yay
so in my example it would be @client.command(name="best", aliases =["cube", "yter"]) right?
sure
Guys I have one question
!d discord.Reaction
class discord.Reaction```
Represents a reaction to a message.
Depending on the way this object was created, some of the attributes can have a value of `None`.
x == y Checks if two reactions are equal. This works by checking if the emoji is the same. So two messages with the same reaction will be considered “equal”.
x != y Checks if two reactions are not equal.
hash(x) Returns the reaction’s hash.
str(x) Returns the string form of the reaction’s emoji.
I have a class (in my Discord bot made using a d.py fork) like this:```py
class MyClass(discord.ui.View):
def init(self):
super().init(timeout=10)
@discord.ui.select(a_parameter=<something>)
...
I want to put a class attribute inside that `<something>` like `@discord.ui.select(a_parameter=self.options)`
How do I achieve this? I just want one class attribute inside the decorator but it shows wrong syntax, this is my issue, any idea how can I work this out?
lemme see, seems like I did something wrong
you cannot
instead u can use add_item in the init
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
I am using add_item atm
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") representing the users that have reacted to the message.
The `after` 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.
Examples
Usage
```py
# I do not actually recommend doing this.
async for user in reaction.users():
await channel.send(f'{user} has reacted with {reaction.emoji}!')
```...
But I have one problem with it
this returns the list of users who reacted with that emoji @slate swan
self.responded doesn't exist for this
u cannot set the callback right?
Why doesn't the bot remove roles?
???
No I am good with the callback part, I took help of the examples
do u have an error handler?
ah okay
I want to find out whether the component was responded to or not
that is what u do in the callback function...
!d discord.ui.Button just subclass this instead and add this inside the view
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
I did that
so change this me stuff and do reactions.users()?
But I want it to remove the components from the message on timeout
read the docs, it returns a generator object
No
And the problem is once I use a component, the timeout restarts instead of stopping
idk how this helps
So it removes the components 10 seconds after I use the component
@maiden fable
I don't want it to do that
that is what it should do...
okay lemme see
But that is what I do not want it to do lol
Ah just do *roles
@rare saddle
I want it to remove the components only if the components were not used, not otherwise
-> Can you please ping me on reply?
Sure
Where to insert it?
well, then u gotta make a counter and set its initial value to 0. increment it in a button click
remove roles method
so i put the users into a list using flatten and then cycle through and delete the reactions?
So?
mhm
yups, but be vary that it may send too many API calls
sorry for not answering soon, I missed your message since I am helping 3 people at once
It's fine haha
This does not work
another error?
oof any traceback?
?
NameError: name 'reaction' is not defined
@maiden fable
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
• Identify the exception raised (in this case ZeroDivisionError)
• Make note of the line number (in this case 2), and navigate there in your program.
• Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
code now
Something like this?```py
class ButtonClass(discord.ui.Button):
def init(self):
self.counter=0
def callback(self,itr):
self.counter=1
#my stuff
class View(discord.ui.View):
def init(self):
super().init(timeout=10)
self.add_item(ButtonClass())
async def on_timeout(self):
if ButtonClass.counter=0:
await self.message.edit(view=None)
self.counter += 1
and no, u did it wrong
you gotta save the button in a class variable
for x in msg.reactions:
users = await
reaction.users().flatten()
print (users)```
no
wait
users = await x.users()
Like button=self.add_item(ButtonClass())?
self.btn = ButtonClass()
self.add_item(self.btn)
if self.btn.counter != 0:
# never used
TypeError: object ReactionIterator can't be used in 'await' expression```
then don't await it
how can i make my bot case insensitive
you cannot
WHAT
you can only make commands case insensitive
commands.Bot(case_insensitive:bool)
why command
asyncio.sleep(60*20)
Dont Work????
how
add case_insensitive=True arg in your commands.BOt
Yea that
Only for commands
Thanks Sarthak (I am literally fucked up rn lmao)
how i can make an embed with every line like a description?
like everything like the smiling face
!d discord.Embed.description
The description of the embed. This can be set during initialisation.
does it work?
could you elaborate wym by "add more lines"?
feels like i'm getting close lol @maiden fable
for x in msg.reactions:
if str(x.emoji) in letters:
users = x.users()
for yy in users:
await msg.remove_reaction(x.emoji, yy)```
any error?
