#discord-bots
1 messages · Page 34 of 1
what is a good discord py tutorial
how could i go on about getting all text channels using a guild id?
one day... i'll make my own tutorial
get the guild object and then guild.text_channels
!d discord.ext.commands.Bot.get_guild -- to get guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.Guild.text_channels -- all text channels
property text_channels```
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.
got it,m thanks
uuh for some reason on_invite_create is not working
Here are my intents
I don't see any errors on the console
Can we see the on_invite_create function?
Is the cog being loaded properly?
the description is quite long
class invite_events 😭
yes
Cog should be named InviteEvents, by the way
oh bruh
Do you get the print statement print("LA VEOOOO") when you create an invite?
for textchannel in guild: print(textchannel)
not exact code
nope
but thats the idea
yeye i know pseudo code
!d discord.Guild.text_channels
property text_channels```
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.
got it
didn't even notice I named it like that
I'll go change it haha
So, leaving the horrible class naming, why isn't it working?
how do i create a webhook in a chanel?
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
so it doesn't do anything when you create invite? even print? and no errors?
tried this, returns
RuntimeError: Timeout context manager should be used inside a task```
nada
what
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
okay so it seems like if I create an invite without modifying its expiring date or stuff like that it wont appear on the audit
pobre robin
Well my bad mr. english 🙄
my native language is spanish mr
hi oki ✌️
hi master✌️
rus... ok

await channel.create_webhook(name='webhook')
RuntimeError: Timeout context manager should be used inside a task```
hola uno duos tres
quadro
el pablo
that was perfect spanish👀
La revolucion
i just want to get help
mi espanol
with? nice pfp btw lol
You gave 1/10 of a traceback and one line of code.
We are not miracle workers.
True he prob didn't put it an an async context.
traceback is 9 letters where did you get 10 from
😭
wdym
My traceback is 10
ty
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
guild = client.get_guild(int(config["guildid"]))
channels = guild.channels
for channel in channels:
if channel.name == 'webhook-test':
await channel.create_webhook(name='webhook')```
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "c:/Users/aisil/Desktop/waifu/main.py", line 132, in main
asyncio.run(create_webhooks())
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "c:/Users/aisil/Desktop/waifu/main.py", line 145, in create_webhooks
await channel.create_webhook(name='webhook')
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\channel.py", line 471, in create_webhook
data = await self._state.http.create_webhook(self.id, name=str(name), avatar=avatar, reason=reason)
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 1117, in __aenter__
self._resp = await self._coro
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client.py", line 448, in _request
with timer:
File "C:\Users\aisil\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 635, in __enter__
raise RuntimeError(
RuntimeError: Timeout context manager should be used inside a task```
Where are you doing this? Inside of a command?
i'm calling the function
Where are you calling it from?
wdym?
Inside where are you calling it from? A command? Event?
from input xD
Should I be worried?
minute 😳
what does that mean?
Sorry? I'm not understanding
im not sure what the error means but it seems like it was invoked in the incorrect spot lol
never seen that error actually
me2
if input is xyz i'm calling asyncio.run(create_webhooks())
so youre running a coroutine while the bot isnt even prepared?
wdym not even prepared
not ready
you would need to run asyncio.run before the bot starts as bot.run is like a blocking loop meaning youre also giving asyncio.run ownership of the loop
Yeah you shouldn't use asyncio.run() for that
It should only be used once in your program to kickstart the asynchronous event loop
and youre trying to get a channel object from the bots cache when the bot hasnt even been deployed lol
aaa, ok
An easy spot to put it in would be inside of a command
should be in a command as told, better for debugging/testing
@bot.command()
async def cheese(ctx):
asyncio.run(create_webhooks())
```??
if i type
!poll hello sir
ok ok
hm hm
done done
if create an embed
question : hello sir
1 : ok ok
2: hm hm
3: done done
how can i brack string like thissssssssssssss
Well no, not like that. Awaiting the coro, I mean
bro
Instructions unclear.
!e print("Hello\nWorld!")
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Hello
002 | World!
read again i men something else
You distracted me with gif
my bad
!e
a= 60
b = 80
c = a+b
print(c)
@winged mason :white_check_mark: Your 3.10 eval job has completed with return code 0.
140
#bot-commands
oh sry my bad
no worries
Yow
I'm still getting this error
Traceback (most recent call last): File "/home/container/main.py", line 9, in <module> bot = discord.Bot(command_prefix='$', activity=activity, status=discord.Status.online, intents=discord.Intents.all()) AttributeError: module 'discord' has no attribute 'Bot'
On my pc it works, but on my host not
what library are you using?
only pycord has that attribute
Wdym libary?
I have installed pycord
how did you install it on your host
its probably clashing with something
run pip show py-cord and show
Cant
pycord or py-cord?
What host u usin?
pycord?
Do i need py-cord
How do i install?
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
in ur pc terminal type these
pip install py-cord
Requirement already satisfied: py-cord in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (2.1.0) Requirement already satisfied: aiohttp<3.9.0,>=3.6.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from py-cord) (3.7.4.post0) Requirement already satisfied: attrs>=17.3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord) (22.1.0) Requirement already satisfied: typing-extensions>=3.6.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord) (4.3.0) Requirement already satisfied: chardet<5.0,>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord) (4.0.0) Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord) (1.8.1) Requirement already satisfied: async-timeout<4.0,>=3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord) (3.0.1) Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.9.0,>=3.6.0->py-cord) (6.0.2) Requirement already satisfied: idna>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<3.9.0,>=3.6.0->py-cord) (3.3)
then ur good to go i guess
and uninstall discord.py
Ok
to prevent any clashing
pip uninstall discord.py
read this tag. Better to invoke pip as a python module
i gave these incase u need some help
yessir
Does anyone know the disnake equivalent to this?
async def balance(self, ctx: commands.Context, member: nextcord.Member = None):
async def balance(self, ctx: commands.Context, member: disnake.Member | None = None):
i fixed the annotation btw lol
not valid paramater annotation , is that something to do with the rest of the code?
thats odd im pretty sure that is a correct parameter annotation
Perplexes me
Is discord.py continued?
ye
So why is everyone using disnake or nextcord and not just discord.py
personal preference
by the time danny came back plenty of devs already switched libraries, and they're still getting maintained so there isnt that big of a reason to switch back
^
Everyone went and found a new library, learnt it, got familiar and then danny was like nvm were back
It was new to the user
wasnt really new either only change mostly was new endpoints and namespaces everything was mostly the same
Yeah, most libs were forks or similar. I just meant people found libraries they hadn’t used before, so they were new, to the user
And it’s a pain converting old projects over to a new library even if it’s just decorators being changed
more like they experimented with the lib and stuck with it, is a better way to say it
me: find and replace😳
getting crazy error when trying to make a discord bot
import discord
TOKEN = "not here for reasons"
client = discord.Client()
@client.event
async def on_ready():
print("{0.user} is now online!".format(client))
client.run(TOKEN)
@slate swan
im on macos
await interaction.response.send_message("hello")
'Button' object has no attribute 'response'
?
I quess you forgot, that button callback function takes the button itself as a parameter too
@client.group(invoke_without_command=True)
async def help(ctx):
embed=discord.Embed(title="Help Commands", color=Color.green)
embed.add_field(name="Moderation", value="!help Moderation", inline=True)
embed.add_field(name="Other", value="!help other", inline=True)
embed.add_field(name="Neutral", value="!help Neutral", inline=True)
embed.set_footer(text="For a more in-depth explination on each command, simply type `!help <command>` (replace <command> with the command you want help with)")
await ctx.send(embed=embed)```
nothing works, the entire group doesnt functoin
🤔
async def <name>(self, interaction) -> async def <name>(self, button, interaction)
oh got it
Did I do something wrong? I thought it would’ve shown the component name in the field name (it’s in hikari-tanjun)
info = {}
for component in ctx.client.components:
cmds = ctx.client.iter_commands()
info[str(component)] = ", ".join([cmd.name for cmd in cmds])
if not obj:
embed = hikari.Embed(
description="""Welcome to DJ BMO's help!
Find all the commands available on this panel.""",
color=0x77F2F2,
)
for component, cmds in info.items():
embed.add_field(name=component, value=cmds, inline=False)```
Traceback (most recent call last):
File "D:\ph\lib\site-packages\discord\ui\view.py", line 423, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Kamal kishore\Desktop\Project 0\commands\admin\poll.py", line 41, in button3
await interaction.response.edit_message(view=self)
File "D:\ph\lib\site-packages\discord\interactions.py", line 782, in edit_message
raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before
mean ?
import discord
from discord.ext import commands
client = commands.Bot(command_prefix=".")
client.remove_command("help")
@client.event
async def on_ready():
print("test")
@client.command()
async def help(ctx):
await ctx.channel.send("pong")
Hey my bot look like this and when i write .help
nothing gonna happend
discord.errors.InteractionResponded: This interaction has already been responded to before
Are you running the bot?
yes
Do you have an on_message?
no
ohhh followup ?
!intents are you intents set up properly?
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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
if you need to, yes
i didnt it
any disadvantage ?
Not necessarily, no
That's a good starting point, then
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix=".")
client.remove_command("help")
@client.event
async def on_ready():
print("test")
@client.command()
async def help(ctx):
await ctx.send("pong")
still nothing
i dont get anything when i write .help
but print("test") i got
You also need intents.message_content = True, and make sure you enable it on your dashboard as well
you mean this?
Right
Do you have intents.message_content = True enabled in your code as well?
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix=".")
client.remove_command("help")
@client.event
async def on_ready():
print("test")
@client.command()
async def help(ctx):
await ctx.send("pong")
Try removing client.remove_command("help")
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix=".")
client.remove_command("help")
@client.event
async def on_ready():
print("test")
@client.command()
async def test(ctx):
await ctx.send("pong")
i changed this command to "test"
and still dont work
how to check for 2 words in on message event
like if 'lol' or 'alex' in message.content:
or doesnt work sadly
Is your bot online?
yes
Set intersection
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Hey @brazen seal! I noticed you posted a seemingly valid Discord API token in your message and have removed your message. This means that your token has been compromised. Please change your token immediately at: https://discordapp.com/developers/applications/me
Feel free to re-post it with the token removed. If you believe this was a mistake, please let us know!
import discord
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.message_content = True
intents.members = True
client = commands.Bot(command_prefix=".")
client.remove_command("help")
@client.event
async def on_ready():
print("test")
@client.command()
async def test(ctx):
await ctx.send("pong")
can someone test this code?
i dont have any idea why it cant work correctly
ty
Does your bot have permissions to message in the channel?
he has admin
(url=ctx.guild.icon.url) ??????????//
..Sorry?
can i set color embed as a hex?
Ya
Lol I got error become i dont have guild icon nvm my mistake
or just numbers of rgb
how
Use the syntax 0x000000 where 000000 is your hex code
where?
Ah if you want to use RGB, use the discord.Colour.from_rgb function
!d discord.Colour.from_rgb
classmethod from_rgb(r, g, b)```
Constructs a [`Colour`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Colour "discord.Colour") from an RGB tuple.
Damned british spelling
color = 0x000000
Not a string
Write this
thanks
i cant add this as a argument
!d discord.Colour typehint kolor to discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)").
There is an alias for this called Color...
i dont understand
kolor: discord.Colour = 00fff7
oh and for the default it'd be better if you did something like kolor: discord.Colour = discord.Colour(00fff7)
Thanks it works
@client.group(invoke_without_command=True)
@commands.cooldown(1,15,commands.BucketType.user)
async def updates(ctx):
embed=discord.Embed(title="Updates", description="Updates to the bot", color=Color.orange)
embed.add_field(name="Help Command Rewrite", value="`!updates help-rewrite`")
embed.add_field(name="New Command", value="`!updates newcommand_1`")
await ctx.send(embed=embed)
its not working, the entire group doesnt work
so i migrated dpy 2.0 having some problems setting up the bot turns on but doesn't respond to my command anything i can do? It also doesn't give off any errors.
@client.group(invoke_without_command=True)
async def help(ctx):
embed=discord.Embed(title="Help Commands", color=Color.green)
embed.add_field(name="Moderation", value="!help Moderation", inline=True)
embed.add_field(name="Other", value="!help other", inline=True)
embed.add_field(name="Neutral", value="!help Neutral", inline=True)
embed.set_footer(text="For a more in-depth explination on each command, simply type `!help <command>` (replace <command> with the command you want help with)")
await ctx.send(embed=embed)```
same with this
its better to subclass the help command but anything that you prefer
subclass?
what error is it giving
the embed doesnt work
u dont even have the command thats why lol
wdym?
can I remove my bot from a server where I am not owner at?
guild.leave()
that'll leave all guilds though
Don't help people when you're asking for help
put the...?
No it doesn't
u dont have a decorator
client.group doesn't exist
()?
It's commands.group
nvm
i can't import buttons 
Are you on 2.0?
where do i put?
.
how can i check it?
before any command
look at the example
How did you install discord.py?
pip install discord.py
Just tell them to read docs
that installs v1.7.3
You can install 2.0 using
python3.8 -m pip install -U git+https://github.com/Rapptz/discord.py (you need python 3.8 or later)
check out the migration guide in the docs
migration guide sucks
well duh use your python
@client.command()
async def example():
print("test")```
like that?
im just saying its not as helpful still having problems with it
Missing the Arg for context
yeah jus an arg
just use py
a what?
very
oh its cool
then why are you starting with a fairly advanced lib
Go learn python first
yeah try to learn both at the same time in a balanced way
oh yes learn easy and hard stuff at the same time
Install git
how
ok
sounds good to me
oh my god
the problem
was, Color.<color>
I had to replace it with one of these: 0x9e0000
How to get id of message which user answering?
@bot.command()
@commands.is_owner()
async def leave(ctx, * , guild_name):
guild = discord.utils.get(bot.guilds, name=guild_name)
if guild is None:
await ctx.reply("I don't recongize that server!")
return
await bot.leave_guild(guild)
await ctx.reply(f"Done, Removed the bot from {guild.name} server!")``` why doesn't that work?
guild.name on last line should be guild_name
It's not the issue, It always doesn't recongize the server
got it from here https://stackoverflow.com/questions/56403367/command-to-make-my-bot-leave-a-specific-guild-discord-py-rewrite
@bot.command()
@commands.is_owner()
async def leave(ctx, * , guild_name):
guild = discord.utils.get(bot.guilds, name=guild_name)
if guild is None:
await ctx.reply("I don't recongize that server!")
return
await guild.leave(guild)
await ctx.reply(f"Done, Removed the bot from {guild.name} server!")``` still not recongizing the server
First it's pnly guild.leave(), and are sure this is the exact server name?
yes
Try it with id
did that too
Try to add that to the beginning of the command and tell me what it says:
print([guild.name for guild in bot.guilds])
['PIF']
That's the server you are trying to leave?
nope
Ok. Are you sure thr bot is currently in the server you do want to leave? And intents are enabled right?
intents = discord.Intents.all()
intents.members = True```
Show where you defined bot
bot = commands.Bot(command_prefix="esk ", intents=intents)
Uh weird
so where do you think the problem came from?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
Oh wait, my bad
Works now
What did u change
I was testing on the test bot and my mistake is I didn't add that bot to other servers.
but when I added it, worked
Lol
Why is button.style typed as an integer when the documentation has string labels for each like danger?
Because the button style actually comes down to an integer I believe, which is what is passed to the API
Button.style returns the corresponding style value from ButtonStyle (idk if that wording is correct), which is an Enum
How can I generate a random code ?
!e
import
secrets secrets.token_hex(15)
@limber bison :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 1
002 | import
003 | ^
004 | SyntaxError: invalid syntax
@limber bison :white_check_mark: Your 3.10 eval job has completed with return code 0.
c3fc
I keep getting rate limited for some reason
!d secrets.token_hex
secrets.token_hex([nbytes=None])```
Return a random text string, in hexadecimal. The string has *nbytes* random bytes, each byte converted to two hex digits. If *nbytes* is `None` or not supplied, a reasonable default is used.
```py
>>> token_hex(16)
'f9bf78b9a18ce6d46a0cd2b0b86df9da'
Do events affect in this?
that's for the number of bytes
no, listening for events won't make you rate-limited
but sending too many requests will
what are you doing with your bot?
I just restarted it several times
and are you hosting it on replit?
@zealous jay
oh
are you spamming, or
i have important question
What's it return ?
Its not sending messages on other servers at the moment tho
In newer discord.py versions it's an int
Im just testing an on_invite_create event
But at the moment I start it I get the warning
show your code, maybe you're hardcoding server ids
Ohk k
or maybe anyone else know it
How can i write hexadecimal color when i have to add 0x to variable with code of oclor?
The event code?
yea
!paste
someone know?
what's get_configured_channel?
I'll paste it
it connects to a mongodb database
and gets the configured channel on that server
you configure it with another command
You can parse it using int(kolor, base=16)
okay so the problem is you're getting rate-limited for no reason?
yeah
Are there any other features in your bot? Or is it just the invite feature causing rate-limits
I'll procced to explain them
When an user joins the server it checks for the configured channel in that server, it also searches if that user has any bans (it checks on the bans the bot saved in the database from every server its in) and sends a message containing the ban count
When a user gets banned it saves the ban in the database
When a user gets unbanned it deletes the ban from the database
When the bots joins a server it fetchs all the bans that guild has and saves them in the database
It also has a few commands to display bans and reason from x user
And the invite thing, when an invite is created it sends a message with info
And there's also some other commands that no one can use except for me and Im not using them so 🤷♂️
Commands seems to work tho but I keep getting that warning when I start the bot
If i edit button lable , is there any rate limit ?
Like i use it in a poll , in which at start when I ping everything more then 10k ppl come at once to vote
Will it able to handle it ?
Is there any formatter for discord.py code?
wdym? it's python code why would you need separate formatter?
I mean, a tool which removes unnecessary indentations
So this is my bot, does anyone know why Im getting rate limited
Shift + Tab 🗿
to remove indents
there are a lot of lines
use black
where u hosting?
Not hosting rn, just testing on my pc
what warning then?
are u doing something in on_ready?
don't change presence in on_ready
and when should I do it?
do a task loop function to change it every 5 seconds
and call the function in on_ready
well it updates when it joins/leaves a server so I will only call it once
instead of looping
and that works well?
yep
then what's your problem?
that I keep getting rate limited for some reason
wtf, if a person wants to change presence once why should he do a loop
.
still dont get, 5 sec loop != every time bot joins a server
well, what's the correct way to update number of servers where the bot is in then?
^^
It does it once when it starts and then updates it when it joins/leaves servers with events
no. thats not better.
a: 5 seconds is too short, you’ll get ratelimited that way
b: discord.Client AND commands.Bot have the activity and status kwarg in their bot constructors.
someone expert here told me to do this
@tasks.loop(seconds=5)
async def status():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} servers!"))
@bot.event
async def on_ready():
status.start()
print("We have successfully logged in as {0.user}".format(bot))```
set presences there
I mean the guild count wont update unless the bot joins/leaves a guild so I think its better to use events
Instead of constantly updating
no problem
very good expert btw
anyways, I keep getting rate limited for some reason 🥲
well if your bot joins servers very fast, like every 5 sec he gets invited, it makes sence to make a loop to not get ratelimited
Again, DO NOT DO ANYTHING IN ON_READY
on_ready is called MULTIPLE times as said in the docs and SHOULD NOT be used for anything even starting a task.
5 seconds is too short of a duration. you'll get ratelimited that way. use something like 5 minutes
I do not have a loop
he is not using it
o
you dont get context
then where to start the task?
he's changing presence in on_ready
yikes.
Here's everything my bot does
In case its something from there
@zealous jay then i shall send you here.
do not change your bot's presence in on_ready as on_ready is not actually made to have stuff really called in it. it's more just a dummy event.
print('BOT IS READY')
by constructor you are talking about this?
yes
if you want to truly get an accurate count on prescense updating when your bot joins a server, make a basic tasks.loop with the duration of 5 minutes so that you dont get ratelimited + it checks for the bot server count every 5 minutes for updates.
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
@zealous jay
well, 1 minute is also enough to not get ratelimited but ok
but isn't an event better?
no
im trying to understand
why not simply use a on_guild_join (or whatever it was) event
its not better necessarily
eh that could prob work idk
thats what Im doing
your bot can get invited / removed from a server a lot of times really fast, and boop baap rate limited
ive had ratelimit issues with 1 minute as well
and you dont see any update in the status right?
thats because the bot is not joining a server currently
also I still need that event because
When the bots joins a server it fetchs all the bans that guild has and saves them in the database
you can use setup hook to change the presence for the first time
why not commands.Bot's __init__?
async def setup_hook():
await bot.wait_until_ready()
await bot.change_presence(...)
bot.setup_hook = setup_hook
cause init dunder is a normal method, not an async one
just make it async😏
setup_hook does work for that BUT you cannot access guild count like that in it.
bot = await Bot(**kwargs)
why not?
😩
wait nvm i just saw the wait_until_ready im stupid
yea~
well, that warning he's getting essentially means that your code is blocking for more than x seconds
should I wait until ready to load cogs?
class Dog:
async def __new__(cls) -> "Dog":
await (instance:=super().__new__(cls)).__init__()
return instance
async def __init__(self) -> None:
pass
async def main() -> None:
await Dog()
😳
it blocks heartbeat
depends, in most cases no
:(
So... where should I change presence then?
lemme just shoot you
please do
@zealous jay do this for the first time
im going with you
and let the on_guild_join events stay
🔫
uuuh 'NoneType' object has no attribute 'change_presence'
full code?
hes so cute😍
async def setup_hook(self) -> None:
await self.change_presence(
status=discord.Status.online,
activity=discord.Activity(type=discord.ActivityType.watching,
name=f'{len(self.guilds)} servers! | g!help'))
self.session = aiohttp.ClientSession()
target_dir = Path.cwd() / 'cogs'
for cog in target_dir.rglob('*.py'):
await self.load_extension(f'cogs.{cog.parent.name}.{cog.stem}')
await cltree.sync(guild=discord.Object(770698123915165747))
self.synced = True
print('All commands are now synced.')
water gun?
👀
check my code again, notice the wait_until_ready ..
oh srry
yea thats enuf for okimii
you love me too much to kill me🥺 😌
btw wait_until_ready is probably not what is designed for setup_hook, which is done before the bot is setup
yes i do
30000 years
yes
🛌
😉
just 2-3 seconds after on_ready, depending on your bots' cache size
is the bot online?
mm yeah then what master said, you cant use wait_until_ready there sadly
async def change_s():
await bot.wait_until_ready()
await bot.change_presence(...)
async def setup_hook():
asyncio.get_event_loop().create_task(change_s())
bot.setup_hook = setup_hook
``` but you can do this
what the hook is this
How many people here work in teams
just create a task loop
asher does 😳
imagine
90% of bots i see have multiple people working on it, surely not necessary 
heh don't get me started on team
L

I'll refrain from commenting on that sarth still here 👀
yes this should for sure work given that asyncio is imported
AND
wait for a few sec
just use a taskloop smh
just bruhing do it in a bot definition and that's it
you cant get the guild count there
why would you need all that to just get it async
whocares
actually you can
but rip dpy, they wont let u
actually you can even make a command
🛌
will any of this fix the rate limit thing?
not necessary
my messages all invisible today
the thing is I don't care about the presence, I just want to avoid getting rate limited for some reason
why are you being rate limited?
I don't know 😭
thats what he's asking for
are you getting rate limited when you start your bot?
yes
yes
Is your bot running on replit?
i kept getting that with a library i used to use, spacing on the name
went away when i switched
you shouldve ignored to prove it
nope, im hosting it on my pc, just testing it
idk if session id is important
I'd suggest set up proper logging with the logging module to see get to the root of the issue
btw its shard id None
that means they are using Bot, not AutoShardedBot
ohkay
I have never used it but I'll try
how do you even get logging messages?
I think discord.py does it
the latest version
idk I updated today and the suddenly appeared lol
yeah it does but im not sure if it should show
oh yeah, i used to use interactions-py, that was the one that would always get me rate limited
because even 1.7.3 had it and i never got the logging messages
i never really get logging messages if its outside of the file im running lmao
🤷♂️
I honestly have no idea and Im confused af
being a programmer in a nutshell
i mean you could just comment out random parts of the code you run on start up and see when it goes away

no thanks
something that can ratelimit you quick is reactions
dont use reactions
thats good
and there's barely any commands
and they are only in my guild lmao
its pretty weird
weird, you'd think reactions are fairly easy for discord to process
theyre not lol
i get the little ratelimited block on mobile all the time since ratelimits on reactions is so low
wasn't there some meme with reactions
like people said there was an easter egg if you reacted really fast a few times and it would mute you
i've never had to use logging 
lol, im planning to study computer science so I should get prepared haha
mhmm nice, same, what are you leaning to be and what degree are you looking for bachelor?
what do you mean by what am I looking for bachelor
like what degree
mhm nice
how to send message visible to one player?
ephemeral
thx
!d discord.InteractionResponse
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
interaction.response.send_message("Text here", ephemeral=True)
can't
wait
nevermind
HELP
ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)
Traceback (most recent call last): File "C:\Users\genni\OneDrive\Documenten\Lars Boost bot\main.py", line 1, in <module> import discord, json, requests, os, httpx, base64, time, subprocess File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module> from .client import Client File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module> from .webhook import Webhook File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module> from .async_ import * File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 52, in <module> from ..channel import PartialMessageable ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)
Make sure discord.py doesn't overlap with third party libs like pycord or disnake
if you're using discord.py
I dont have discord.py
then what?
Oh
Yeah fixed this, but this not
File "C:\Users\genni\OneDrive\Documenten\Lars bot\main.py", line 2, in <module>
from discord.ext import tasks, commands
ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)
well I guess I'll ask again tomorrow about the rate limit thing
?
python -m pip update discord
ERROR: unknown command "update"
upgrade?
-U
python -m pip uninstall discord && python -m pip install discord
isn't it -U?
Collecting discord Using cached discord-1.7.3-py3-none-any.whl (1.1 kB) Collecting discord.py>=1.7.3 Using cached discord.py-1.7.3-py3-none-any.whl (786 kB) Requirement already satisfied: aiohttp<3.8.0,>=3.6.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from discord.py>=1.7.3->discord) (3.7.4.post0) Requirement already satisfied: async-timeout<4.0,>=3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (3.0.1) Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (6.0.2) Requirement already satisfied: chardet<5.0,>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (4.0.0) Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (1.8.1) Requirement already satisfied: attrs>=17.3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (22.1.0) Requirement already satisfied: typing-extensions>=3.6.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (4.3.0) Requirement already satisfied: idna>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (3.3) Installing collected packages: discord.py, discord Successfully installed discord-1.7.3 discord.py-1.7.3
but this installs discord.py
And i dont need discord.py bcs then i'll get more errors
what are you trying to use then? some fork?
No importing tasks
no they are using discordpy, just accessing the tasks
ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)
Still get this err
you need discord.py for that. make sure you pip install discord.py first ( pip show discord to confirm that its installed)
pip install discord[tasks]
it is, they are trying to access tasks
But if i install discord.py
i'll get these
Traceback (most recent call last): File "C:\Users\genni\OneDrive\Documenten\Lars Boost bot\main.py", line 1, in <module> import discord, json, requests, os, httpx, base64, time, subprocess File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module> from .client import Client File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module> from .webhook import Webhook File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module> from .async_ import * File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 52, in <module> from ..channel import PartialMessageable ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)
the discord package is not discord.py.
!pip discord.py
!pip discord
A mirror package for discord.py. Please install that instead.
no, discord comes with discord.ext
they are different
yea. mirror package. Meaning discord installs discordpy
Boys help me :p
theres no guarantee for that.
Collecting discord.py>=1.7.3
Using cached discord.py-1.7.3-py3-none-any.whl (786 kB
look at their installation above, it does install it
doesnt means it essentially doesnt override it
C:\Users\genni\OneDrive\Documenten\Lars bot>pip show discord Name: discord Version: 1.7.3 Summary: A mirror package for discord.py. Please install that instead. Home-page: https://github.com/Rapptz/discord.py Author: Rapptz Author-email: License: UNKNOWN Location: c:\users\genni\appdata\local\programs\python\python310\lib\site-packages Requires: discord.py Required-by:
Then ill get these
Traceback (most recent call last): File "C:\Users\genni\OneDrive\Documenten\Lars Boost bot\main.py", line 1, in <module> import discord, json, requests, os, httpx, base64, time, subprocess File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module> from .client import Client File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module> from .webhook import Webhook File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module> from .async_ import * File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 52, in <module> from ..channel import PartialMessageable ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)
!d discord.channel.PartialMessageable
class discord.PartialMessageable```
Represents a partial messageable to aid with working messageable channels when only a channel ID is present.
The only way to construct this class is through [`Client.get_partial_messageable()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_partial_messageable "discord.Client.get_partial_messageable").
Note that this class is trimmed down and has no rich attributes.
New in version 2.0...
did you delete it first?
yes i delete it first
Found existing installation: discord 1.7.3 Uninstalling discord-1.7.3: Would remove: c:\users\genni\appdata\local\programs\python\python310\lib\site-packages\discord-1.7.3.dist-info\* Proceed (Y/n)? y Successfully uninstalled discord-1.7.3
This is so frustraded
how to delete message?
!d discord.Message.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other people’s messages, you need the [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") permission.
Changed in version 1.1: Added the new `delay` keyword-only parameter.
Can you help me
reinstall discord.py
How
pip uninstall discord.py
pip install discord.py
cant
Collecting discord.py Using cached discord.py-1.7.3-py3-none-any.whl (786 kB) Requirement already satisfied: aiohttp<3.8.0,>=3.6.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from discord.py) (3.7.4.post0) Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (1.8.1) Requirement already satisfied: typing-extensions>=3.6.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (4.3.0) Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (6.0.2) Requirement already satisfied: attrs>=17.3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (22.1.0) Requirement already satisfied: chardet<5.0,>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (4.0.0) Requirement already satisfied: async-timeout<4.0,>=3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py) (3.0.1) Requirement already satisfied: idna>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<3.8.0,>=3.6.0->discord.py) (3.3) Installing collected packages: discord.py Successfully installed discord.py-1.7.3
Requirement already satisfied: idna>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<3.8.0,>=3.6.0->discord.py) (3.3)
With discord.py still gets this error, without discord.py get the other error
C:\Users\genni\OneDrive\Documenten\Lars Boost bot>py main.py Traceback (most recent call last): File "C:\Users\genni\OneDrive\Documenten\Lars Boost bot\main.py", line 1, in <module> import discord, json, requests, os, httpx, base64, time, subprocess File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 25, in <module> from .client import Client File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 53, in <module> from .webhook import Webhook File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\__init__.py", line 12, in <module> from .async_ import * File "C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 52, in <module> from ..channel import PartialMessageable ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (C:\Users\genni\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\channel.py)
you need to run the first command first... did you?
Yes i did
someone can help please?
the method returns None lol
i dont think interaction send_message returns anything
yeah
Can u help me?
it does
None
it returns None😏
also why are you not asleep
well sarth is already helping you
its 1 am
shhh
He's offline, ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)
it returns
it returns None
the coro itself
it sends the message, ofc
but the function doesnt give you a message
okay and how can i delete it?
it returns None, but the coro makes a HTTP request theyre not the same
that you can delete
hey, are you guys able to help me with something?
How?
yes?
Broooo
Someone help me
from discord.ext import commands, tasks ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)
!d discord.Interaction.delete_original_response
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete "discord.InteractionMessage.delete") in case you do not want to fetch the message and save an HTTP request.
Can u help me?
Make sure you don't have any folders or files named "discord"
I dont have
Try reinstalling then
I already did 5 times
the whole issue is probably due to name clashing lol
How do i reinstall?
Wdym
can you get the user id and then mention them like you can with slack
something like:
user = msg.get('user_id')
await msg.channel.send(f'hello <@{user}>')
Collecting discord Using cached discord-1.7.3-py3-none-any.whl (1.1 kB) Collecting discord.py>=1.7.3 Using cached discord.py-1.7.3-py3-none-any.whl (786 kB) Requirement already satisfied: aiohttp<3.8.0,>=3.6.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from discord.py>=1.7.3->discord) (3.7.4.post0) Requirement already satisfied: chardet<5.0,>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (4.0.0) Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (6.0.2) Requirement already satisfied: async-timeout<4.0,>=3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (3.0.1) Requirement already satisfied: typing-extensions>=3.6.5 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (4.3.0) Requirement already satisfied: yarl<2.0,>=1.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (1.8.1) Requirement already satisfied: attrs>=17.3.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (22.1.0) Requirement already satisfied: idna>=2.0 in c:\users\genni\appdata\local\programs\python\python310\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<3.8.0,>=3.6.0->discord.py>=1.7.3->discord) (3.3) Installing collected packages: discord.py, discord
You have 2 different interactions so it's confused on which one to delete
the Context class has an author attr that returns a Member or User which you can use the id attr which both of them have lol
f"<@{user_id}>"
``` is good enough for that
??
thx Robin
you dont need msg.get('user_id')
whatever it means...
wait is user id already a variable?
its an attribute
its the way I remember from the slack api
If you have the ID, you can easily just mention it without doing anything special
to msg?
to message and context
!d discord.Member.mention
property mention```
Returns a string that allows you to mention the member.
File "C:\Users\genni\OneDrive\Documenten\Lars Bot 2\main.py", line 2, in <module> from discord.ext import commands, tasks ImportError: cannot import name 'tasks' from 'discord.ext' (unknown location)
removed word Boosts
Ok?
boost bot
Yes?
Yeah it's probably some sort of naming issue then
idk why you removed it
But how can i fix?
Yes but how can i fix
You'll need to take a good look at your filesystem and see if you've got any other folders or files named "discord" or similar that could be clashing
hey anyone here a discord dev looking for a job?
you check dirs that have such a name or check if you have a corrupted installation
!rule 9 ig
oh my bad
How do i check corrupted instaltion?
you can check its src or errors if they get raised in its src or you can use pip list if you have any other packages that can cause name clashing
I'm guessing it's not a corrupt installation given you just reinstalled it
yup
But do what Okimii said, people get confused between pip install discord and pip install discord.py, may cause issues
But i have litterly the same bot in other file and other name & it works
So use that instead
``Package Version
aiohttp 3.7.4.post0
anyio 3.6.1
async-timeout 3.0.1
attrs 22.1.0
certifi 2022.6.15
chardet 4.0.0
charset-normalizer 2.0.12
colorama 0.4.4
datadispatch 1.0.0
discord 1.7.3
ffmpeg-python 0.2.0
future 0.18.2
h11 0.12.0
httpcore 0.14.7
httpx 0.21.3
idna 3.3
imageio-ffmpeg 0.4.7
multidict 6.0.2
numpy 1.23.2
pip 22.2.2
py-cord 2.1.0
requests 2.27.1
rfc3986 1.5.0
setuptools 63.2.0
sniffio 1.2.0
typing_extensions 4.3.0
urllib3 1.26.11
yarl 1.8.1``
pycord 😭

i said to check if there are any third party
Looks like we found it
perfect, that works thanks a lot
Doesn't pycord use the same namespace as discord?
yup
yes
I'm guessing that's what the error is then
What?
This is why one should always use venvs when possible
i responded first with checking if there are 3rd party libs and what i get?
Ok what do i need to do?
Uninstall pycord or uninstall discord.py
idc if you dont believe me but i was about to say "this screams pycord and dpy clashing" 😭 ✌️
WARNING: Skipping pycord as it is not installed.
Pycord is just all around strange huh
very
py-cord
py-cord, not sure if that matters though
But i need py-cord
bruh
blame pycord for having trash src
Then uninstall discord.py
already done
I'm getting this if uninstall py-cord File "C:\Users\genni\OneDrive\Documenten\Lars Boost bot\main.py", line 1, in <module> import discord, json, requests, os, httpx, base64, time, subprocess ModuleNotFoundError: No module named 'discord'
wbruh
Well now make sure you have pycord installed, given we just told you to uninstall pycord
You need to have either discord.py installed or pycord, but not both
players = [ctx.author, arg]
answer_1 = ""
answer_2 = ""
async def rock_callback(interaction):
if not interaction.user in players:
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: This isn't your interaction menu.", colour=discord.Colour(error(ctx.guild.id))))
if interaction.user == ctx.author:
if answer_1 == "":
answer_1 = "rock"
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":AdvancedBotTick: You selected `rock`.", colour=discord.Colour(success(ctx.guild.id))))```
UnboundLocalError: local variable 'answer_1' referenced before assignment```
YES
it's a rock paper scissors command... i have very less idea what's going wrong here, isnt my code logic fine?
It works lets go
answer_1 is defined outside the function, so you either use View class to define it inside __init__ or use global, but I think global is bad in this case
Go with a dedicated view subclass, it's best for passing state around
yeah ^^
oh
since you referenced the global and then you tried to reassign a value to it meaning the error was raised because the value was assigned locally and referenced before lol
pretty sure it went over the head for op
what
wut what?👀
huh
im not sure what you mean lol
players = [ctx.author, arg]
class Rock:
def __init__(self):
answer_1 = ""
async def rock_callback(interaction):
if not interaction.user in players:
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: This isn't your interaction menu.", colour=discord.Colour(error(ctx.guild.id))))
if interaction.user == ctx.author:
if answer_1 == "":
answer_1 = "rock"
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":AdvancedBotTick: You selected `rock`.", colour=discord.Colour(success(ctx.guild.id))))
rock.callback = rock_callback
r = Rock()``` Does this seem right
i'm sorry im new to using classses in such cases
I still got the same error in this code
and interaction would be self so allot of attribute errors will be raised lol
simple English smh i meant op prolly didn't understand what u said 
i still dont understand your point
... ;-; nvm

im on my way to doing it (hopefully correctly)- how do i define ctx.author and the player, and also how do i pass the players list i defined earlier?
@button(lowercase)- you define the function in a class, not in
__init__method, so put it one indent lower (remove one tab) async def func():will require getting self since it's a class + callback of a button will always get button argument, so it will beasync def rock_callback(self, interaction, _button):- you can make ctx a required argument in View's init method (
def __init__(self, ctx)) and doself.ctx = ctx, so you can useself.ctxin your callback - answer_1 doesn't get it self, so you need to do
self.answer_1 == ''instead of justanswer_1(same withanswer_1 = "rock") - to define players you can again simply do
self.players = your_players_listso then you can useself.playersin callback
lowecrase
ohh
Thanks
Basically, view = RPS(ctx, playerlist) is what i shall also do in my rps command code right
yeah
similar to functions while calling a class
Thanks! ill do all of this and get the code working
also, btw, PEP 8: line should contain maximum of 120 symbols (just recommendation)
alright
NameError: name 'button' is not defined. Did you mean: 'Button'?```
well, discord.ui.button then, since you didnt import it
lowercase...
oh there too?
they're different
oop okay!
Got it!
!pep 9001 says otherwise
PEP 9001 does not exist.
No
haha
Python Enhancement Proposals (PEPs)
&pep 9001
wth
at least 120 characters long
what the actual f
oh april 1
its august 14
half the august passed
:(((
Oh mo work soon
Is this correct- my bot doesnt respond to it though
class RPS(discord.ui.View):
def __init__(self, ctx, players):
self.answer_1 = ""
self.answer_2 = ""
self.ctx = ctx
self.players = players
@discord.ui.button(label="Rock", style=discord.ButtonStyle.green, emoji="🪨")
async def rock_callback(self, interaction):
if not self.interaction.user in self.players:
return await self.interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: This isn't your interaction menu.", colour=discord.Colour(error(self.ctx.guild.id))))
if self.interaction.user == self.ctx.author:
if self.answer_1 == "":
self.answer_1 = "rock"
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":AdvancedBotTick: You selected `rock`.", colour=discord.Colour(success(self.ctx.guild.id))))```
I can't read photos
skill issue
Ratio 😡
with the assumption that Exenifix was on mobile so he cant properly read codeblocks on discord, i used a bin for him
wait what??
error is a function which fetches a specified color from the database in my code
bruh why's it called error
Run formatter on that code
Why tf does it take guild id
i can rename it to something else
Because my bot has a feature where people can customize the embed color scheme in each server individually
Interesting
that's why
and what happens when you execute the command?
No those are met
I just used try except
got this error: 'RPS' object has no attribute 'children'
It's not printing anything in raise
?
raise ain't a function bro
uh oh
What's the correct syntax for it?
raise e
Ohh okay
only raise works too
Nope not printing anything
print(traceback.format_exc()) lolmao
What's the problem, I haven't read the full convo
Oh interaction stuff, good luck
just searched that error in this channels history
yeah
actually yes
Is that a valid solution to this issue
Yup it is there but uhh i don't understand why super init is used- mind explaining that pls (im trying to understand the code and not blindly copy ))
super() is instance of the original class (that you are subclassing, right now - discord.ui.View), so you have your own __init__ and super().__init__() is calling the original init for the class
Oh
Works so far!
TypeError: RPS.rock_callback() takes 2 positional arguments but 3 were given though when i click the button
show your callback func
class RPS(discord.ui.View):
def __init__(self, ctx, players):
super().__init__()
self.answer_1 = ""
self.answer_2 = ""
self.ctx = ctx
self.players = players
@discord.ui.button(label="Rock", style=discord.ButtonStyle.green, emoji="🪨")
async def rock_callback(self, interaction):
if not self.interaction.user in self.players:
return await self.interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":x: This isn't your interaction menu.", colour=discord.Colour(error(self.ctx.guild.id))))
if self.interaction.user == self.ctx.author:
if self.answer_1 == "":
self.answer_1 = "rock"
return await interaction.response.send_message(ephemeral=True, embed=discord.Embed(description=f":AdvancedBotTick: You selected `rock`.", colour=discord.Colour(success(self.ctx.guild.id))))```
why is my channel the only one that no one has talked in
in my list I said that callback will always take button argument so you need async def ...(self, interaction, _button):, you probably wont use _button, but it is given and you are forced to take it
oh