#discord-bots
1 messages · Page 1092 of 1
ok so i went for a crude approach ||atleast it works||
view.message = await ctx.send()
await view.wait()
for item in view.children: item.disabled = True
await view.message.edit(view=view)
adding multiple partial emoji in discord server?
partial emoji?
class discord.PartialEmoji```
Represents a “partial” emoji.
This model will be given in two scenarios:
• “Raw” data events such as [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add")
• Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.reactions "discord.Message.reactions")...
!d discord.Guild.create_custom_emoji
await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a custom [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji") for the guild.
There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.
You must have the [`manage_emojis`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis "discord.Permissions.manage_emojis") permission to do this.
adding sticker?
!d discord.Guild.create_sticker
await create_sticker(*, name, description, emoji, file, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Sticker`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Sticker "discord.Sticker") for the guild.
You must have [`manage_emojis_and_stickers`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_emojis_and_stickers "discord.Permissions.manage_emojis_and_stickers") permission to do this.
New in version 2.0.
Does timeout has a time limit?
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
how do I fix it?
import line?
file;
Does import discord work
i don't have it in my code
my first line is from discord.ext import commands
I am asking you to check if it works
from discord.ext import commands
first try importing discord
import discord
from discord.ext import commands```
ok
!d disnake.Member.timeout
await timeout(*, duration=..., until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Times out the member from the guild; until then, the member will not be able to interact with the guild.
Exactly one of `duration` or `until` must be provided. To remove a timeout, set one of the parameters to `None`.
You must have the [`Permissions.moderate_members`](https://docs.disnake.dev/en/latest/api.html#disnake.Permissions.moderate_members "disnake.Permissions.moderate_members") permission to do this.
New in version 2.3.
Yes
hunter u know how to post reqs or upload using python? or requests lib...
i mean can i make like 1 year,2 year timeout
ghost ping owo
no, there's a limit of some days, 18 probably
lemme recheck
If I parse IDs to test_guilds of Bot constructor (disnake), will it sync the commands for other guilds or nah
nope, the commands may stay in other guilds but they shouldn't functions
sarth
Ok is there any way to speedup the sync for certain guilds but make it sync the other commands for the rest of guilds
wots the error?
do you call the disabled function?
no it's just a rudimentary bot so the error should show
yeah like view.on_timeout = disabled
Assigning functions isn't a good idea, subclass View instead
yeah subclassing is fine but it's just a small button reaction part a tick and a cross
Better practice + better looking + more readable + less flooding + most likely will work
commands take the guilds kwarg too right, so you can just mention the commands which are guild specific there instead of the Bot constructor
No I mean like make some guilds sync like they are test ones but still sync the commands for other guilds
also i should find out at least what is going wrong right?
Not command-specific
It could be internal problem
do u think like it could be a bug or some problem with the dpy lib i can't think of any other reason
Why not just do this
class View(discord.ui.View):
async def on_timeout(self):
...
view = View(timeout=15)```
i did that now
Did you install it?
Traceback (most recent call last):
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 467, in _actual_conversion
return converter(argument)
TypeError: ABCMeta.__new__() missing 2 required positional arguments: 'bases' and 'namespace'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 476, in _actual_conversion
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "ABCMeta" failed for parameter "member".```
this is my Error when i run my command
here is my command
@commands.has_permissions(kick_members=True)
async def mute(ctx, member=discord.Member,reason="No reason"):
guild=ctx.guild
mutedrole=discord.utils.get(name="Muted")
if not mutedrole:
await ctx.send(f"No Muted Role Found in {ctx.guild}..Creating One Now")
await ctx.send("Wait..")
await guild.create_role(name="Muted")
await ctx.send("Done...")
if member == ctx.author:
em1=discord.Embed(title="Mute Err",description=f"{ctx.author} You can't mute Yourself",colour=discord.colour.random())
await ctx.send(embed=em1)
for channel in guild.channels:
await channel.set_permissions(mutedrole, speak=False, send_messages=False, read_message_history=False, read_messages=False)
em2=discord.Embed(title="**Sucsessfully Muted**",description=f"{member.mention} Has been Muted",colour = discord.colour.random())
em2.add_field(name="Reason",value={reason},inline=False)
em3=discord.Embed(title="**You have been Muted**",description=f"{member.mention} Has been Muted in {ctx.guild}",colour = discord.colour.random())
em2.add_field(name="Reason",value={reason},inline=False)
await ctx.send(embed=em2)
await member.add_roles(mutedrole, reason=reason)
await member.send(embed=em3)```
this is my command
@hot plaza
help
pls @hot plaza
anyone help
Ignoring exception in command mute:
Traceback (most recent call last):
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 467, in _actual_conversion
return converter(argument)
TypeError: ABCMeta.__new__() missing 2 required positional arguments: 'bases' and 'namespace'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 552, in transform
return await self.do_conversion(ctx, converter, argument, param)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 505, in do_conversion
return await self._actual_conversion(ctx, converter, argument, param)
File "e:\VSC and PYcharm py projects\venv\lib\site-packages\discord\ext\commands\core.py", line 476, in _actual_conversion
raise BadArgument('Converting to "{}" failed for parameter "{}".'.format(name, param.name)) from exc
discord.ext.commands.errors.BadArgument: Converting to "ABCMeta" failed for parameter "member".
@client.command()
@commands.has_permissions(kick_members=True)
async def mute(ctx, member=discord.Member,reason="No reason"):
guild=ctx.guild
mutedrole=discord.utils.get(name="Muted")
if not mutedrole:
await ctx.send(f"No Muted Role Found in {ctx.guild}..Creating One Now")
await ctx.send("Wait..")
await guild.create_role(name="Muted")
await ctx.send("Done...")
if member == ctx.author:
em1=discord.Embed(title="Mute Err",description=f"{ctx.author} You can't mute Yourself",colour=discord.colour.random())
await ctx.send(embed=em1)
for channel in guild.channels:
await channel.set_permissions(mutedrole, speak=False, send_messages=False, read_message_history=False, read_messages=False)
em2=discord.Embed(title="**Sucsessfully Muted**",description=f"{member.mention} Has been Muted",colour = discord.colour.random())
em2.add_field(name="Reason",value={reason},inline=False)
em3=discord.Embed(title="**You have been Muted**",description=f"{member.mention} Has been Muted in {ctx.guild}",colour = discord.colour.random())
em2.add_field(name="Reason",value={reason},inline=False)
await ctx.send(embed=em2)
await member.add_roles(mutedrole, reason=reason)
await member.send(embed=em3)
it is discord.utils.get(ctx.guild.roles, name='Muted')
👍🏻
also do
member: discord.Member, *, reason
mine?
no not urs
yeah that part too well i didn't see all of it
because if the role is missing, the mutedrole would be still None Even if u create it
u should probably do smth like this```py
mutedrole = await guild.create_role(name="Muted")
member: discord.Member not member=discord.Member
Also please format your code
It's pain to read
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'os' has no attribute 'evniron'
@commands.hybrid_command(aliases=['shorteen'])
async def bitly(self,ctx, *, link):
bitlykey = os.evniron['bitly_key']
async with aiohttp.ClientSession() as session:
async with session.get(f'https://api-ssl.bitly.com/v3/shorten?longUrl={link}&domain=bit.ly&format=json&access_token={bitlykey}') as req:
r = await req.read()
r = json.loads(r)
new = r['data']['url']
em = discord.Embed(title='Shorten Link',
color=0x2f3136)
em.add_field(name='Shortened link', value=new, inline=False)
await ctx.send(embed=em)
i have imported os why do i get this error
os.evniron
its env not evn
is there a way to get the client.user.default_role?

check_role = discord.utils.get(user.guild.roles) will this return the NAME of the rank?
so i need to a word from user
how do I get the name from a rank
then a desired number of times it to be repeated
i can't get it
can someone help with it?
@spi.command()
async def ping(ctx,*,pong,number):
await ctx.send(pong*number)
also i started discord.py today
help would be appreciated
check_role = discord.utils.get(user.guild.roles, name = "the role's name")
or check_role = discord.utils.get(user.guild.roles, id = int)
now I want to get the role name
"
pretend I don't know the name of the role
i want to know what role this person has
oh
ty
returns the user's roles
how can I check if a specific role is among the persons role(s)
can someone help please 😭
why r u trying to times a string and a integer
just want it be a bit of spam
yes, I want it to work like that.
@bot.command()
async def ping(ctx, number = 1):
for i in number:
print("pong")
hold on
lemme test it
actually u test it
yeah on that
!e @bot.command()
async def ping(ctx, number = 1)
for i in number:
print("pong")
@scarlet aurora :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | async def ping(ctx, number = 1)
003 | ^
004 | SyntaxError: expected ':'
woops
!e @bot.command()
async def ping(ctx, number = 1)
for i in number:
print("pong")
@scarlet aurora :x: Your eval job has completed with return code 1.
001 | File "<string>", line 2
002 | async def ping(ctx, number = 1)
003 | ^
004 | SyntaxError: expected ':'
!e @bot.command()
async def ping(ctx, number = 1):
for i in number:
print("pong")
@scarlet aurora :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'bot' is not defined
which one works
how to make the uptime show like this <t:1624385691:R>
@commands.hybrid_command()
async def uptimeee(self,ctx):
uptime = datetime.utcnow() - start_time
hours, remainder = divmod(int(uptime.total_seconds()), 3600)
minutes, seconds = divmod(remainder, 60)
days, hours = divmod(hours, 24)
await ctx.send(f"** I have been online for `{days}` Days, `{hours}` Hours, `{minutes}` Minutes, `{seconds}` Seconds.**")
@bot.command()
async def ping(ctx, number = 1):
for i in number:
print("pong")```
if role.id in user.roles?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Style is R
@dim sentinel lemme know if it works
is there a way to get client(my bot) role? the main/default one?
u didn't define what pong is here right? also it's in strings
hey, in my help command i define my command signature like thispy signature = self.helpcommand.get_command_signature(command)
it returns whole command syntax like the following
!d discord.Guild.self_role @slate swan
property self_role```
Gets the role associated with this client’s user, if any.
New in version 1.6.
how do i define command and syntax differently
all u do is >ping 2103
how do i define a!pokestat and <pokemon> separately? anyone?
Traceback (most recent call last):
File "C:\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Python310\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'int' object is not iterable
@bot.command()
async def ping(ctx, num: 1):
for range(num):
print("pong")```
number is undefined, and youre looking for range(num)
still aint working, imma try importing math module once
an int isnt an iterable
@commands.command()
@commands.is_owner()
async def promote(self, ctx, user: discord.Member = None):
roles = []
for role in user.roles:
roles.append(role.name)
Assault_Marine = discord.utils.get(user.guild.roles, name='Assult Marine')
Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')
if user is None:
await ctx.send("Choose someone to promote")
else:
if 'Assault Marine' in roles:
await user.remove_roles(Assault_Marine)
await user.add_roles(Seeker_Marine)
await ctx.send(f"Sucsesfully promoted ``{user}``")``` Can someone tell me why this wont work?
oh ye
code
just write the bytes to a file?
with open("uwu.jpg", "wb") as f:
f.write(BytesObject)
''' async '''
import aiofiles
async with aiofiles.open("uwu.jpg", "wb") as f:
await f.write(BytesObject)
what's the error?
traceback*
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
it's better to move the user is None to the top
and instead of i (in the image below) use a list comprehension which may be slightly faster
roles = [role.name for role in user.roles]
and it's good if you name the parameter user to member as it is gonna be an instance of discord.Member and not discord.User for which the usage of user as a parameter name would have been suitable
can I see the whole traceback?
@scarlet aurora ^ and this
Might as well kick/ban him instead
ahem
Traceback (most recent call last):
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\llVll\Desktop\Luna Bot\cogs\utils.py", line 100, in promote
await user.remove_roles(Assault_Marine)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\member.py", line 822, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'```
nice, Assault_Marine is None
my bad, sorry hunter
Traceback (most recent call last):
File "main.py", line 2, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
how would i get the message content of a message that a user replied to?
for example,
if i sent this message
and then replied to the message on top with a command
how would the bot get the first message
like I run !uwu while replying to your message rn, the bot should reply to the same message I replied to, right?
i just need it to get the message content of the message that the !uwu command was replied to
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
Reinstall dpy
can I know why it says (unknown location)?
Corrupted installation
it couldnt find such folder meaning your installation is corrupted
I am making a starboard on my bot but it doesn't work (i'll send code)
shouldn't you have sent it along with the message-
@client.event
async def on_raw_reaction_add(payload):
emoji = payload.emoji
guild = client.get_guild(payload.guild_id)
channel = await guild.get_channel(payload.channel_id)
message = await channel.get_message(payload.message_id)
if emoji.name == "⭐️":
async with client.db.cursor() as cursor:
await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
data = await cursor.fetchone()
if data:
starData = data[0]
channelData = await guild.get_channel(data[1])
for reaction in message.reactions:
if reaction.emoji == "⭐️":
if reaction.count >= starData:
embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
await channelData.send(embed=embed)
using discord.py 2.0
the error is on line 5 TextChannel can not be awaited
channelData = await guild.get_channel...
remove the await.
then i get another error
get message isnt a coro neither
on line 6 message does not have get_message()
^
!d discord.abc.Messageable.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/latest/api.html#discord.Message "discord.Message") from the destination.
and if i remove that i'll get no errors and the code doesn't work
you first need to differentiate between normal methods and coroutines get_xs in discord.py are normal functions and don't need to be awaited
fetch_xs are coroutines/awaitables
Union[discord.Emoji, discord.PartialEmoji]```
what is this
idk how fetch works
!d typing.Union it means an argument/variable can be a discord.Emoji or discord.PartialEmoji
typing.Union```
Union type; `Union[X, Y]` is equivalent to `X | Y` and means either X or Y.
To define a union, use e.g. `Union[int, str]` or the shorthand `int | str`. Using that shorthand is recommended. Details...
Nyc
I have import that?
where do you need it?
In code?
@slate swan how can i fix it then?
they just work like get but you need to await them too,
you are making a request to discord when you do that
ok
for?
is that a command argument typehint?
from typing import Union
so i need to change it to await fetch_message(payload.message_id)
as a typehint
await channel.fetch_message(...
First i have to install that module right?
await channel.fetch_message(payload.message_id)
No its a stdlib
Ohk
?
Also you dont need to use partialemoji since it will use the convert method of EmojiConverter from your argument @lyric apex
there's a seperate converter for PartialEmoji isn't it
@slate swan
await channel.fetch_message(payload.message_id)
Yes but whats the point of parsing a partialemoji
indeed, its of no use unless you are trying to access emojis which the bot cannot see.
show updated code?
sure
@client.event
async def on_raw_reaction_add(payload):
emoji = payload.emoji
guild = client.get_guild(payload.guild_id)
channel = await channel.fetch_message(payload.message_id)
message = await channel.get_message(payload.message_id)
if emoji.name == "⭐️":
async with client.db.cursor() as cursor:
await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
data = await cursor.fetchone()
if data:
starData = data[0]
channelData = await guild.get_channel(data[1])
for reaction in message.reactions:
if reaction.emoji == "⭐️":
if reaction.count >= starData:
embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
await channelData.send(embed=embed)
Which lib
notice your channel variable defination, variables and methods don't come out of thin air. its bot/guild.get/fetch message
channel = await channel
What
You don't define channel
isee
now i fixed it but it still doesn't work and i have no errors
@client.event
async def on_raw_reaction_add(payload):
try:
emoji = payload.emoji
guild = client.get_guild(payload.guild_id)
channel = guild.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
if emoji.name == "⭐️":
async with client.db.cursor() as cursor:
await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
data = await cursor.fetchone()
if data:
starData = data[0]
channelData = await guild.get_channel(data[1])
for reaction in message.reactions:
if reaction.emoji == "⭐️":
if reaction.count >= starData:
embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
await channelData.send(embed=embed)
except Exception as e:
print(e)
add print statements after each action to see where it stops working
i think there is something wrong with this
Just debug
yes it is not an awaitable as mentioned 3 times above.
idk what that means
Not awaitable expression
Coro is coroutine, you can read about some asynchronous programming concepts in asyncio docs
!d asyncio
Hello World!
import asyncio
async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')
asyncio.run(main())
```...
still doesn't work
Create a breakpoint in that event and run a debug session
ok
Pycharm has very convenient debug imo
str(reaction.emoji) for your condition @stable leaf
ok
Well would be str(emoji)
where?
if str(emoji) == "⭐️":```
so this is the endpoint
@client.event
async def on_raw_reaction_add(payload):
emoji = payload.emoji
print("emoji")
guild = client.get_guild(payload.guild_id)
print("guild")
channel = guild.get_channel(payload.channel_id)
print("channel")
message = await channel.fetch_message(payload.message_id)
print("message")
if str(emoji) == "⭐️":
print("1")
async with client.db.cursor() as cursor:
print("2")
await cursor.execute("SELECT starLimit, channel FROM starSetup WHERE guild = ?", (guild.id,))
print("3")
data = await cursor.fetchone()
print("4")
if data:
print("5")
starData = data[0]
print("6")
channelData = guild.get_channel(data[1])
print("7")
for reaction in message.reactions:
print("8")
if reaction.emoji == "⭐️":
print("9")
if reaction.count >= starData:
print("10")
embed = discord.Embed(title="New Star Board Message", description=f"{message.content}", color=0x000000)
print("11")
await channelData.send(embed=embed)
print("12")
str(reaction.emoji)
It stops on 1 or what
Or message
@stable leaf btw do you have an error handler
yes
traceback
only thing i have
if str(message.emoji) == "⭐️":
AttributeError: 'Message' object has no attribute 'emoji'
...
error
Bruh
then i have syntax error
this
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
Your emoji is emoji not the message.emoji (it doesn't exist)
so what then
You also have a ton of warnings that tell you that you use bad naming convention and you just ignore them 😔
i am confused
@stable leaf
mf stop talking and read
i dont have any
youll understand more
Click problems
but those are not for this one
That's just code style, telling you how to do it right
sam, i mentioned you thrice for your check 
Do print(emoji)
show your loop part
Does the if condition get passed
ok
The problem comes from his loop part, first check passed he needs to use str() function again
!e print("\u2b50")
@vale wing :white_check_mark: Your eval job has completed with return code 0.
⭐
How can I fix this?
AttributeError: 'Message' object has no attribute 'context'
This
That's in another function ig
His first function passed after he used the str() function, i asked him to show his actual for loop part
Nice
and that is the same
so i just need to do there \u2b50
yes
thx to everyone for letting me waste your time
message.content
thanks
thx @vale wing , @slate swan , @crisp drift , @slate swan , @slate swan
Oh god
Got close to automute due to mentions lol
What's the limit?
let me try real quick /j
Haha
imagine getting muted for being grateful 
imagine pinging every moderator / helper / admin / owner
imagine not living on earth
Imagine being banned and unable to get help
Is it possible to give your bot a gif pfp
Hi.
i have this code:
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
await self.find_or_insert_user(message.author)
ctx = await self.bot.get_context(message)
if ctx.command is not None:
return
if message.author.bot is True or message.guild is None:
return
await self.db.execute(
"UPDATE warns set for_add = for_add + 1 where user_id = ? and guild_id = ?",
(message.author.id, message.guild.id),
)
await self.db.commit()
Its not adding up
@commands.command()
async def promote(self, ctx, user: discord.Member = None):
if user is None:
await ctx.send("Choose someone to promote")
roles = [role.name for role in user.roles]
Assault_Marine = discord.utils.get(user.guild.roles, name='Assault Marine')
Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')
if user is None:
await ctx.send("Choose someone to promote")
else:
if 'Assault Marine' in roles:
await user.remove_roles(Assault_Marine)
await user.add_roles(Seeker_Marine)
await ctx.send(f"Sucsesfully promoted ``{user}``")``` This still does not work, also there is no traceback, it just does not remove the rank and add the new rank, do you know why this is happening @slate swan
sadly not
@commands.command()
async def promote(self, ctx, user: discord.Member = None):
if user is None: return await ctx.reply("Choose someone to promote")
roles = [role.name for role in user.roles]
Assault_Marine = discord.utils.get(user.guild.roles, name='Assault Marine')
Seeker_Marine = discord.utils.get(user.guild.roles, name='Seeker Marine')
if 'Assault Marine' in roles:
await user.remove_roles(Assault_Marine)
await user.add_roles(Seeker_Marine)
else: await user.add_roles(Assault_Marine)
await ctx.send(f"Sucsesfully promoted ``{user}``")
The last time iirc Assault Marine role was None
hmm?
The error
oh
it's cuz I spelt assault wrong
this seems like a single guild command, i wonder why don't they use IDs
it works now, no traceback
for my bot i have custom roles for each level like mee6 they can set however they want
ikr
Nice
typos...
Yea just made a PR
i remember i once did pip freeze > requeirments.txt
Nice
and a min later i was like where is my txt
Nice
https://github.com/Py4Js/PyScript-React
Bruh this project is nice but no docs or getting started guide 😔
PyScript wrapper for React https://github.com/pyscript/pyscript - GitHub - Py4Js/PyScript-React: PyScript wrapper for React https://github.com/pyscript/pyscript
Would love to see when someone runs the ot tag
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
I once forgot to change keyboard (I am russian so I have to switch them) and typed куйшщкубуьеы.ече
Nice
Lmao
Tbh that happens pretty often
Understandable
😳 thats why you use poetry and let it configure all the stuff itself.
Lol
thats a lot of stars
that is the official discord docs
People with several layouts can relate
ur a contributor there?
No
owner?
No
...
that is the github for https://discord.dev bro
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
I like that thing but it failed to install scikit learn and idk how to configure it for docker so I typically go with pip + venv
ah, fair
where can I find the list of permissions for running bot commands?
u guys know how to upload a file online to a cloud bin and get link for that file the file is an image
Varies
just tick admin in ur bot dev page
Should I write a wrapper for discord API in java (JDA sucks imo)
I have a problem when I clique on a button at my bot can you help me pls
Don't use 3rd party libs
yeah u know a way?
button.callback
Checkout the API docs of the file uploader
nooooooooo
like to run a bot command
my system's screenshot tool has builtin imgur integration so i just shows an option to upload to imgur and copy the link there itself
yes
its not screenshot its a pil image
why do u want that btw?
lemme see
In fact all libs you install from pypi are 3rd party cuz they are not builtins but I get what you meant
Lmao I agree with u
bit of mass image editing dont want it in my local files
you can still use imgur
oh ok
imgur has a python wrapper ?
U can use aiohttp
Aiohttp exists but ok
they do have an api so
!pypi imgur-python
!pip imgur-python
Nice
Sus
can u send link?
Tho its not updated anymore
thx
Just use aiohttp it's cool
its sync as well
these libs ain't async
Just thought about that
aiohttp is alright but idk how to post files or upload them nor do i know any site for that ._.
!pip asyncgur
DEPRECATED
Nvm sorry
-.- I almost made him use aiohttp directly
Let's make a new wrapper for that
WHY tf did u have to do that
That lib is from 2020 tho
assert response.success == True and response.status == 200
sus
Most likely got old enough
Indeed
Nice AssertionError ngl
lemme try thx a lot tho
i just store the image's bytes in a remote db
i need it as link tho lemme tell u why coz discord bots dont allow file attachment editing
so rn i dump the image in a dump channel then take the attachment url and use it in embed
Nice
but it causes a delay like arnd a second
__import__("sys").path.insert(1, ".") any comments?
that's what I said to just copy one link of the image and use that instead
wdym the image is diffrent everytime
@shrewd apex why not upload the image to a log channel or smth then save the url in the db and then use the url everytime u need to upload (show) the image
like every time the command is run?
if he understands that, I'm going to hell
yeah it a character walking on a map what do u expect position changes
Nice, u r making a game
smh
Reptiles have already made yr life one, no need to go to another one
and every user has a character and their xy axes
Might as well make it a standalone game
i dont think i am so good at graphics to do that
Just use pixel art ezzz
in pycord is this not a valid way to remove roles in a list?
for role in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
oldroles = discord.utils.get(ctx.guild.roles, name=role)
await player.remove_roles(oldroles)
u wanna see what i am doing rn?
Sure ig
i dont think my command is doing anything
here
this is the only part that isn't doing anything
no errors or anything
since remove_roles takes in Roles i used get to get the role
try printing oldroles
how to make the uptime command show like this <t:1624385691:R>
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
mmm
just use "ROLE IDS" instead of "ROLE NAMES" if you are doing this command for a single server.
!d discord.Guild.get_role saves you from utils.get
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
but how will make it in timestamp ?
read the docs. it's pretty clearly written there
this is not a javascript server.
get(category) is returning undefined which does not have any such property you used, and discord.gg/djs is where this belongs to
rnames = []
for role in player.roles:
rnames.append(role.name)
trole = discord.utils.get(ctx.guild.roles, name=team)
if rnames in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
for role in [983770855161094224, 983770930834714685]:
oldroles = ctx.guild.get_role(role)
await player.remove_roles(oldroles)
await player.add_roles(trole)
elif rnames not in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
await player.add_roles(trole)
i tried to take the for loop out from before and use id to print old roles which works, it prints out the roles one at a time however when implemented it doesn't do anythin?
Nice, JS errors
because you are contradicting of what you are doing
hmmmm
i made this mistake once
it haunted me for a solid 2 weeks
wait what do you mean
haunts me to think about that thing
Any idea?
try
rnames = [role.name for role in player.roles]
[await player.remove_roles(ctx.guild.get_role(role)) for role in [983770855161094224, 983770930834714685] if ['Tokyo Fart Sniffers', 'Baltimore Bughas'] in rnames]
await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))
I know that looks a bit messy but I was just too lazy to type
Why first remove then add...
could you explain the brackets for the first await?
idk what team is
I'll break it into parts
could u try to with the lib that u just sent i am getting an error when trying to upload a local image they said either url or bytes i am getting error in the bytes url is wroking fine
how do you get the Bytes?
i tried in two way one was to read binary and then bytearray
with open(..., "rb") as file ?
and other i just opened the image as pil
both same error
\dacite\core.py", line 75, in from_dict
raise MissingValueError(field.name)
dacite.exceptions.MissingValueError: missing value for field "id"
yes but no
!d PIL.Image.Image.tobytes
?
Image.tobytes(encoder_name='raw', *args)```
Return image as a bytes object.
Warning
This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use [`save()`](https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save "PIL.Image.Image.save"), with a BytesIO parameter for in-memory data.
nice
FastAPI is hella weird 💀
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
Nice
Won't be surprised if ot is the most used tag but would be surprised if it ain't
rnames = [role.name for role in player.roles]
#does the same thing as
rnames = []
for role in player.roles:
rnames.append(role)
await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))
this basically is a role adding while getting the Role object inside the add_roles
this is equivalent to
uwu_role = discord.utils.get(ctx.guild.roles, name=team)
await player.add_roles(uwu_role) #ofc how can my examples not be uwu
then comes the main part
[await player.remove_roles(ctx.guild.get_role(role)) for role in [983770855161094224, 983770930834714685] if ['Tokyo Fart Sniffers', 'Baltimore Bughas'] in rnames]
is if I break it down to simple words, is just a for loop
await player.remove_roles(ctx.guild.get_role(role)) gets the role as well as removes it from the player (though this is not a good practice, preferably make a getch. a getch is a logic which fetches stuff if the same query result was not found the in the cache for which get methods are responsible)
for role in [role_ids] is equivalent to a for loop as you can see
if [role_names] in rnames just checks if the role names are in rnames and in that case, removes the role from the player after getting the Role object
reading that list comprehension in simple words - if role_names are not in rnames, then, player.remove_roles -> role, while role is iterated through role_ids
did I spam or what
i hate it how they named modules in PascalCase
@left idol
logging module wants to meet you
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
they have classes and functions as camelCase but atleast that doesnt create confusion between files and classes
but an stdlib and no snake_case 😔
same error still
Use aiohttp @shrewd apex
the wrapper is prolly outdated
I can help u with aiohttp if u have any issues
Hunter is so kind
i see will try tom u mean using the api directly?
Your wish
seems thats the best way
Tho aiohttp gonna make yr life easier imho

API Status
Status for the API can be found at status.imgur.com!
Getting Started
Imgur's API exposes the entire Imgur infrastructure via a standardized programmatic interface. Using Imgur's API, you can do just about anything you can do on imgur.com, while using your pro...
what r we talking about?
Imgur API
yeah i normally try with ready made wrappers first if they fail well u gotta do it on ur own
yea never used it
just wrap the api yourself
yea
Ngl I prefer aiohttp in all the cases (with the exceptions being APIs like discord's)
wdym?
i see
will do sir/maam
ok
Discord API is more difficult if u wanna try using the Raw API from scratch since it involves reconnecting, ready and so on
then use aiohttp and do it?
Huh? Did u even read what I said
and what does it need by ready
why would you use aiohttp if youre only gonna use the REST api?
I did
hm yeah, point
why not?
without a wrapper
@shrewd apex try out this example and send us the result
how do I run my bot through cmd line?
dpy only uses aiohttp because of the gateway an in this case the only usage here is the REST api, no?
python main.py
yeah i saw the api will do tom
U still need aiohttp to connect to the wss
he needs the thrill
you dont need a websocket for the REST api?
ehhh
what do you want him to use instead? httpx?
lamo
I was talking about directly using the API like ourselves implementing the connection, handle all the stuff without using any wrapper
good answer but you can use requests no?
yes blocking requests, sure!.
i thought about kangeroo-sockets
Nice, best of luck with that @slate swan
you said raw api, you shouldve said gateway as well bro
smh
there's nothing wrong with requests...
I'mma just go
but dc bots require to run a cmd 10 times a sec
guess not
They wanna go back to pre v1 period when dpy used to be sync
um okay... no comments.
if i have an async function and a class with sync function and i initialise the class in the command and someone else runs the same command will the class content for the first guy to run the command get overwritten as well?
i would still use aiohttp / httpx for making requests in an async environment, especially when its one of the dependencies of library im already using instead of using a blocking requests lib
if you create an instance inside of the command, no.
yeah it really depends on the application
they are making a bot so..
yeah i call/initialise the class in the command and use that class object
then youll be fine
thx👍
discord canary releases updates like crazy
!e
class A:
b: int
def a(c):
d = A().b = c
print(d)
a(1)
a(2)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
import asyncio
import requests
def blocking_func():
var = requests.get("...")
return var.json()
asyncio.get_event_loop().run_in_executor(None, blocking_func())
idk why but okay
how do you even get canary beta program?
Normal discord eats RAM like crazy
1 GB RAM and still lagging 💀
my discord goes boom
there is an exe on their website
notavirus.exe ?
same with ptb
discord_canary.exe or smth
lol
DiscordCanarySetup.exe*
yea you could be working woth futures and stuff but like just use asyncio
yep the difference is, you can have canary and another instance at the same time, but not publictestbeta and another instance
Really?
why not make a task?
Why not just use aiohttp
I swear I've barely used asyncio, I always forget about the create_task method, don't call me out on that now, like seriously
ok
why install requests when you already have aiohttp installed as a dependency of discord.py 🤨
asyncio.get_event_loop().run_in_executor(None, blocking_func)*
Please tell me when u have the answer
U don't call the func inside the run in exec func
sarth or hunter make an intents system for nakano im lazy
Lemme finish sesquid first. Totally not gonna take months
and then your table gets dropped
what is it about?
that isnt me lol
!e
import asyncio
def blocking_func():
print("uwu")
asyncio.get_event_loop().run_in_executor(None, blocking_func())
imagine whats going through that dude's head rn
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:6: DeprecationWarning: There is no current event loop
002 | uwu
Nice nick
im joking lol
non windows moment
lmao
i love you❤️
i dont wanna deal with bytewise operations
- this is the best impl i've seen in all libraries 😔
@slate swan u ever used FastAPI?
Told u it doesn't work 🤷♀️
On the verge of getting a stroke while using it
i never made something which would use that
!e
import asyncio
def blocking_func(text: str):
print(text)
asyncio.get_event_loop().run_in_executor(None, blocking_func("uwu"))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:6: DeprecationWarning: There is no current event loop
002 | uwu
PyLance wanna have a meeting with u
(asyncio.get_running_loop() or asyncio.new_event_loop()).run_in_executor(None, blocking_func("uwu"))
Still dk why they removed the get_event_loop method
i think create_task works better in asher's case, since he doesnt actually need to wait for the function to return a value
Yea
its a discord bot, so bot.loop would be the best thing to use :)
I was just confirming that works, okimii could you stop doing that, it's so so annoying
its a general case calm down
iirc in 2.0 u cannot access it directly or smth
ok
idk someone here had an issue with that before
time to dig into the src and look for an internal private variable 
lmao
I mean its accessible but dpy raises an error
what var?
bot.loop, or any other way round
hmm?
@slate swan it will still block the whole event loop if u call the function lol
nice
I use pycharm
i use em all depending on my mood but pycharm mostly
Oh nvm then
huh?
what u even tryna show
you just said bot.loop raises an error...
no comments
Cannot find the msg
was it me i asked abt pil regarding this b4?
No, it was an error someone had a few days ago regarding bot.loop prolly it was smth else then
i see
u get an error when u try to access it in a sync function
Maybe unsafe though, with how discord.py works internally
Ah, my bad
try:
book = await loop.run_in_executor(None, parse_ebook, request.name)
except Exception as e:
return Response(e, 500)
Nice this doesn't wanna work
Lmao the error is still raised even after the try except for some reason
what error?
AttributeError
what book?
?
Does it error if you use get_running_loop
It should as long as it isn’t called before the bot is started
And it bypasses discord.py protection
its not a bot
Oh ok
can u show code?
I am raising the error myself to test out the try except
that try except will and should only work if book = await loop.run_in_executor(None, parse_ebook, request.name) fails
just by doing bot.loop? cause it works for me
Yea it raises an error in sync functions
Ryuga clarified
maybe because its closed
Discord.py will raise error when loop isn’t started
how could I code some kind of ping logger, so what do I need to use for that? like who pinged, channel and add the message link as a button
It’s just a sentinel value until then
Hm
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
!d discord.Message.mentions
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.
thanks
hey, i modified the default minimal help command and get this now, how can i get rid of [command=None]
Please tell me what to do?
!d discord.ext.commands.Bot.get_emoji
get_emoji(id, /)```
Returns an emoji with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
are you sure those are valid emojis
@client.event
async def on_message(message):
if message.author.guild_permissions.manage_messages:
But the console write the use not has permission etc.. how can i make it ignore the error?
because this problem spam my console
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
hmm
!d discord.ClientUser
class discord.ClientUser```
Represents your 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.
i have an idea
add py if message.author.id == bot.user.id: return at the top of your on_message func
yea
anyone?
how did you obtain the ids
you mean the arguments?
yeah, i am using the default help command
my problem is this: I dont want to see this, because i know the problem
So
theres no a!help in there, what its currently showing is default
i dont want [command=None] there
do print(str(physics)) after getting the emoji
lemme help u
show the line where you get each commands name
then just do command_name.split(" ")[0]
def format_command_help(self, no, command):
signature = self.helpcommand.get_command_signature(command)
syntaxcommand = signature.split(" ")[0]
syntaxinput = signature.split(" ")[1]
docs = self.helpcommand.get_command_brief(command)
return f"{no}. **{syntaxcommand}** `{syntaxinput}`\n{docs}"```
theres your problem
it added a colon at the beginning
what a second
wait*
i just realized that lol
So it is necessary
try doing await ctx.send(f'{message}')
makes sense but have a look at it
i dont get individual command names, it gets all commands at once
do py def format_command_help(self, no, command): signature = self.helpcommand.get_command_signature(command) syntaxcommand = signature.split(" ")[0] syntaxinput = signature.split(" ")[1] docs = self.helpcommand.get_command_brief(command) return f"{no}. **{syntaxcommand}** `{syntaxinput}`\n{docs}" if syntaxinput != "[command=None]" else return f"{no}. **{syntaxcommand}**\n{docs}"
i do want <pokemon> though
This is how I find it:
if i do that i wont see [command=None], but i wont see <pokemon> either
lemme edit message
edited
OHH
makes a lot of sense now, thanks a lot
bruh
what is that
not the message object
lmao
send the content you want to send, like "Hello world" or whatever
send {hacker}
!paste
comparison of the first thing i wrote vs a rewrite, can you tell which is which just visually 
mhm yes i can read that
i can totally tell the difference in the code
hey, can someone help me solving this error message ?
Ignoring exception in command ibf:
Traceback (most recent call last):
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\arsbu\Documents\CODE\PKbot\test.py", line 72, in ibf
if abs(functions_product(i) - goal) < float(pr):
TypeError: unsupported operand type(s) for -: 'float' and 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: unsupported operand type(s) for -: 'float' and 'str'
there you go
the full code : https://paste.pythondiscord.com/carojufihi
the right one is way neater looking
This is if something does not work in embed
says the person that did the rewrite
after reviewing prs i learnt to NEVER trust when the person that requested the pr also says the rewrite is nicer
then try name=f"{hacker}"
or name=f'''{hacker}'''
just keep changing quotes till it works 👍
help
!e print("lol" - 1.0)
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | TypeError: unsupported operand type(s) for -: 'str' and 'float'
Dear, tell me what is wrong. I don't think he sees the timeS variable, but why?
@commands.has_role(982744620792426537)
@commands.command(name = "мут", aliases = ["замутить", "muut"])
async def command_ban(self, ctx, member: discord.Member, reason, time: int, *, time1):
try:
mute = discord.utils.get(ctx.message.guild.roles, name ="Мут")
await ctx.channel.purge(limit = 1)
await member.add_roles(mute)
if time > 0:
if time1 == ["m", "M", "м", "М"]:
timeS = time * 60
time2 = 60
if time1 == ["h", "H", "ч", "Ч"]:
timeS = time * 3600
time2 = 3600
if time1 == ["d", "D", "д", "Д"]:
timeS = time * 86400
time2 = 86400
else:
time = 'До разбирательств'
memberName = member.name
memberTag = member.discriminator
author = ctx.author.name
tag = ctx.author.discriminator
embed = discord.Embed(
title=(f"Был забанен {memberName}#{memberTag}"),
color= 0xff0000
)
embed.set_footer(
text="| Правительство SK",
icon_url= ctx.guild.icon_url,
)
file1 = discord.File("./ImageS/mut.png")
embed.set_image(url='attachment://mut.png')
date = datetime.datetime.today()
await ctx.send(file=file1, embed=embed)
os.remove("./ImageS/mut.png")
if timeS > 0:
await asyncio.sleep(timeS)
await member.remove_roles(mute)
except discord.Forbidden: return
!paste
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.
@quaint epoch i got it right, thanks a lot. but heres another problem 😂
timeS wouldnt be assigned only if the condition is true in your nested if tree
my buttons work fine, just says interaction failed everytime i press them
rip
then they don't work fine
i mean they scroll and everything
i'd say defer the action/check your call backs
yes i know it's something with float and int but i can't find how to fix that
@bot.command()
async def avatar( ctx , member: discord.Member=None):
if member is None:
member = ctx.author
await ctx.send(member.avatar.url)```
i want that my bot will show the avatar but it wont? what will i do
you make a goal return a number lol
like the discord avatar
you can use or member = member or ctx.author and you would need to use an embed
ok thx
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
i dont know what you mean
uh i do this to make buttons work only for author
async def interaction_check(self, interaction):
"""Only allow the author that invoke the command to be able to use the interaction"""
return interaction.user == self.ctx.author```
in which statement?
everything
bro
pls tell
@bot.command()
async def avatar( ctx , member: discord.Member=None):
if member is None:
member = ctx.author
await ctx.send(member.avatar.url)```
just fix the indents
i tried to fix by adding goal = float(goal.content)
and i now get this error ```C:\Users\arsbu\Documents\CODE\PKbot\testpy\Scripts\python.exe C:/Users/arsbu/Documents/CODE/PKbot/test.py
Ignoring exception in command ibf:
Traceback (most recent call last):
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\arsbu\Documents\CODE\PKbot\test.py", line 13, in ibf
goal = float(goal.content)
AttributeError: 'str' object has no attribute 'content'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\arsbu\Documents\CODE\PKbot\testpy\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'content'
does for me...
they just had messed up indents thats all
if youre not going to satisfy the member argument why have it?
not really
🙂
I already don't like not having
member = member or ctx.author
whoop there it goes
?
i am struggling with buttons, my buttons do the work but gives interaction failed error
I wrote (.123 @slate swan reaction 1 m) but it still gives an error
@commands.has_role(982744620792426537)
@commands.command(name = "123")
async def command_mutes(self, ctx, member: discord.Member, reason, time: int, *, time1):
try:
mute = discord.utils.get(ctx.message.guild.roles, name ="Мут")
await ctx.channel.purge(limit = 1)
await member.add_roles(mute)
if time > 0:
if time1 == ["m", "M", "м", "М"]:
timeS = time * 60
time2 = 60
if time1 == ["h", "H", "ч", "Ч"]:
timeS = time * 3600
time2 = 3600
if time1 == ["d", "D", "д", "Д"]:
timeS = time * 86400
time2 = 86400
else:
time = 'До разбирательств'
if time > 0:
await asyncio.sleep(timeS)
await member.remove_roles(mute)
except discord.Forbidden: return
how do i fix i t
how can i connect the bot to a website to make a dashboard?
Does discord.py support slash commands now?
yep
so my question is simply how can i get rid of this annoying "Interaction failed" thingy? Everything works well, and the buttons also do work. Once the button finished loading, and the action got performed, it simply says "Interaction failed" for no reason
You need to defer the interaction
await interaction.response.defer()
dont want the unnecessary message
There won’t be any message
oh?
For deferring button interactions
where do i do that
How are u making the buttons?
sec
@ui.button(emoji='⏮️', style=discord.ButtonStyle.gray)
async def first_page(self, button, interaction):
await self.show_page(0)
@ui.button(emoji='◀️', style=discord.ButtonStyle.gray)
async def before_page(self, button, interaction):
await self.show_checked_page(self.current_page - 1)
@ui.button(emoji='🗑️', style=discord.ButtonStyle.gray)
async def stop_page(self, button, interaction):
self.stop()
if self.delete_message_after:
await self.message.delete(delay=0)
@ui.button(emoji='▶️', style=discord.ButtonStyle.gray)
async def next_page(self, button, interaction):
await self.show_checked_page(self.current_page + 1)
@ui.button(emoji='⏭️', style=discord.ButtonStyle.gray)
async def last_page(self, button, interaction):
await self.show_page(self._source.get_max_pages() - 1)```
Put it in the functions with button decorators
is there a specific discord server for coding discord bots?
like not just a subset of the python server?
there is
well
There's a discord.py one, and each of the other libraries also have one
@karmic marsh
Put await interaction.response.defer() in the functions with @ui.button
i cant await in there 
They are async tho
oh it's in the channel desc also
Uh I’m on phone so idk how to new line for a code block
@ui.button(emoji='⏮️', style=discord.ButtonStyle.gray, await interaction.response.defer())```
are you telling me to do this
cause this aint making any sense to me
But put it within the function that’s under the decorator
ohhhh
@ui.button(emoji='⏮️', style=discord.ButtonStyle.gray)
async def first_page(self, button, interaction):
await self.show_page(0)
await interaction.response.defer()```
like this?
Yes but if show_page Is a slow function then you should defer before it
👍
now it aint even turning the page, and the interaction error remains untouched 😂
2.0
yesterday
Then swap button and interaction in the function parameters
oh o.o
THANKS A LOT!!
its working awesome now
👍
It messed my code up when it was changed too
I also check the weekly updates in the discord.py server
oh wait, i do this
async def interaction_check(self, interaction):
"""Only allow the author that invoke the command to be able to use the interaction"""
return interaction.user == self.ctx.author```
for obvious reasons
so if someone other than author reacts
will they see interaction failed or not
o.0
They would see interaction failed
I usually just send an ephemeral message and return false
interaction.response.send_message(…, ephemeral=True)
@slate swan thank you for the explanation but it still doesn't look like its working:
rnames = [role.name for role in player.roles]
if rnames in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
[await player.remove_roles(ctx.guild.get_role(role)) for role in [983770855161094224, 983770930834714685] if ['Tokyo Fart Sniffers', 'Baltimore Bughas'] in rnames]
await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))
elif rnames not in ['Tokyo Fart Sniffers', 'Baltimore Bughas']:
await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))
are you trying to check if any of the users roles are in ['Tokyo Fart Sniffers', 'Baltimore Bughas']?
I’m trying to check if the user has any of those roles and if they do remove them
if rnames in ['Tokyo Fart Sniffers', 'Baltimore Bughas'] so with this, it is checking if a list is inside a list ([] in []) which wont work in this case. so you should use this to check if any the roles are within that if any(rname in ['Tokyo Fart Sniffers', 'Baltimore Bughas'] for rname in rnames)
but you should assign ['Tokyo Fart Sniffers', 'Baltimore Bughas'] to a varaible before to not create a list a lot more times than needed
bruh
I'm already struggling with this and I've barely done anything
why does ```py
TOKEN = os.getenv('DISCORD_TOKEN')
client.run(TOKEN)
not work when ```py
client.run(ndjislIFNUISndjskd.etc.etc)
works just fine?
I have a file called .env that contains this:
# .env
DISCORD_TOKEN={"ndjislIFNUISndjskd.etc.etc"}
it doesn't give me any errors, it just doesn't do anything
how to create buttons with discord.py 1.7.3?
allteams = ['Tokyo Fart Sniffers', 'Baltimore Bughas']
trole = discord.utils.get(ctx.guild.roles, name=team)
[await player.remove_roles(ctx.guild.get_role(role)) for role in [983770855161094224, 983770930834714685] if any(rname in allteams for rname in rnames)]
await player.add_roles(discord.utils.get(ctx.guild.roles, name=team))```
so something like this then
i think that should work
also instead of ctx.guild.get_role(role) you can just use discord.Object(id=role) because remove_roles jsut needs the id
ye got it to work, thank you!
but on another topic, when i use interaction.defer() and then a long task followed by at the end interaction.message.edit, why does it say the application did not respond?
i have to interaction.followup.send()?
Followup is when u reacted already
U need to await interaction.defer() if I'm right
I wanted to ask does anyone know how I can import the name of a text data into my responses
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I was able to fix the problem myself
is there a disnake discord server?
I'm running into this issue:
SyncWarning: Failed to overwrite commands in <Guild id=983259662411501578> due to 403 Forbidden (error code: 50001): Missing Access
warnings.warn(
So, I had a question that was trying to be solved in #help-cheese, so can someone try and finish helping me. Thank you if so.
You probably don’t have the applications.commands scope
yeah... looks like I was supposed to put that in the url
is split() still a method of message
in message.content, yes
Please help.
y'all use disnake?
I can't figure out how to get the current guild of the bot
or rather, iterate through the list of connected guilds and ID one by name
can you send me the doc link to split() please
this should work but it doesn't:
guild = disnake.utils.get(disnake.Client.guilds, name=GUILDNAME)
Come on please!
!d str.split
str.split(sep=None, maxsplit=- 1)```
Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done (thus, the list will have at most `maxsplit+1` elements). If *maxsplit* is not specified or `-1`, then there is no limit on the number of splits (all possible splits are made).
If *sep* is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, `'1,,2'.split(',')` returns `['1', '', '2']`). The *sep* argument may consist of multiple characters (for example, `'1<>2<>3'.split('<>')` returns `['1', '2', '3']`). Splitting an empty string with a specified separator returns `['']`.
For example:
Ignoring exception in command search:
[{'text': "This is just a regular little gummy bear,\xa0\nand I've decided to destroy it. To do this\xa0\xa0", 'start': 0.24, 'duration': 5.68}, {'text': "I just have to get a vial, and I'll add a small\xa0\namount of something called potassium chlorate.\xa0\xa0", 'start': 5.92, 'duration': 5.68}, {'text': 'After that I just have to heat it up,\xa0\nuntil it all melts into a nice goop.', 'start': 12.32, 'duration': 4.24}, {'text': 'At this point it should be pretty good, and I\xa0\ncan carefully drop in the poor little gummy bear.', 'start': 19.52, 'duration': 5.36}, {'text': 'Almost immediately the potassium chlorate started\xa0\nripping it apart, and oxidizing it into water,\xa0\xa0', 'start': 28.64, 'duration': 6.32}, {'text': "and CO2 gas. Within just several seconds\xa0\nthough the reaction's already done,\xa0\xa0", 'start': 34.96, 'duration': 5.12}, {'text': 'and my little gummy bear, no longer exists.', 'start': 40.88, 'duration': 2.96}]
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\core.py", line 172, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\cogs\youtube.py", line 21, in lnk
check = json.load(transcript)
File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'list' object has no attribute 'read'
my code:
@commands.command(name="search")
async def lnk(self, ctx, youtube_vid, term):
video_id = youtube_vid
transcript = YouTubeTranscriptApi.get_transcript(video_id)
print(transcript)
keyval = term
check = json.load(transcript)
if keyval in check:
print('Found term in:')
print(f'check')
why're you using json.load?
im using a guide to search json arrays and thats what is shows
EX
Example-1: Search key in simple JSON data
The following script shows how to search if a particular key exists in a JSON string or not. Here, a variable named customerData is defined to store the JSON data. The value of the key will be taken as input from the user. loads() method of JSON module is used to load JSON data in the variable named customer. Next, ‘in’ operator is used to search the key.
#!/usr/bin/env python3
# Import json module
import json
# Define json data
customerData ="""{
"id": "3425678",
"name": "John Micheal",
"email": "john@gmail.com",
"type": "regular",
"address": "4258 Poplar Chase Lane, Boise, Idaho."
}"""
# Input the key value that you want to search
keyVal = input("Enter a key value: \n")
# load the json data
customer = json.loads(customerData)
# Search the key value using 'in' operator
if keyVal in customer:
# Print the success message and the value of the key
print("%s is found in JSON data" %keyVal)
print("The value of", keyVal,"is", customer[keyVal])
else:
# Print the message if the value does not exist
print("%s is not found in JSON data" %keyVal)
yes, it's unneeded, check the docs/source code of get_transcript
ok so removing that dropped the error but im trying add functionality to search the json
i have an example of the json output
[{'text': "This is just a regular little gummy bear,\xa0\nand I've decided to destroy it. To do this\xa0\xa0", 'start': 0.24, 'duration': 5.68}, {'text': "I just have to get a vial, and I'll add a small\xa0\namount of something called potassium chlorate.\xa0\xa0", 'start': 5.92, 'duration': 5.68}, {'text': 'After that I just have to heat it up,\xa0\nuntil it all melts into a nice goop.', 'start': 12.32, 'duration': 4.24}, {'text': 'At this point it should be pretty good, and I\xa0\ncan carefully drop in the poor little gummy bear.', 'start': 19.52, 'duration': 5.36}, {'text': 'Almost immediately the potassium chlorate started\xa0\nripping it apart, and oxidizing it into water,\xa0\xa0', 'start': 28.64, 'duration': 6.32}, {'text': "and CO2 gas. Within just several seconds\xa0\nthough the reaction's already done,\xa0\xa0", 'start': 34.96, 'duration': 5.12}, {'text': 'and my little gummy bear, no longer exists.', 'start': 40.88, 'duration': 2.96}]


