#discord-bots
1 messages · Page 933 of 1
@tasks.loop(seconds = 5)
async def loop(self):
for channel in self.guild.text_channels:
if channel.name == "batt-done":
print('test')
await channel.delete()
use this see if it even is finding the channel
yup so self.guild isnt working
try
async def loop(self, ctx):
for channel in ctx.guild.text_channels:
if channel.name == "batt-done":
print('test')
await channel.delete()
idk if u can call more arguments
did not bring
event
ctx didn't work
they told me to use task
@tasks.loop(seconds = 5)
async def loop(self, ctx):
for channel in ctx.guild.text_channels:
if channel.name == "batt-done":
print('test')
await channel.delete()```
yeah something like this
@client.event
async def on_guild_channel_delete(channel):
#do sum
Hello, I have an error and I don't know how to solve it, can someone help me please?
when ever a channel gets deleted it runs the code u put it
huh
its an event
Exception has occurred: ModuleNotFoundError
No module named 'discord.ext'; 'discord' is not a package
During handling of the above exception, another exception occurred:
File "D:\Hack\Visual studio code\discord.py", line 2, in <module>
from discord.ext import commands
File "D:\Hack\Visual studio code\discord.py", line 1, in <module>
import discord
only when it gets triggerd it runs
It is supposed to delete automatically whenever a channel is renamed to #batt-done
how can i fix this error to make my bot work?
how would I put a timer, it needs to be checked every 30mins
where ?
What does this mean
IndentationError: unindent does not match any outer indentation level
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
poor indentation
well what if someone renames it and still need to do something in the channel, it will just get deleted
yes, the discord.py extension is installed on my visual studio code
this means?
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
someone renames the channel, then they want to log something which is in the channel. Since it has no timer it will just delete immediately when it is renamed
no every 30mins
https://cdn.drijon.tk/chrome_qsT46mlir5.png
so line 22 should go one forward and line 23 one backwards or what?
ups 20 - 21 - 22
@client.event
async def on_guild_channel_update(channel):
if after.channel_name == "test":
await channel.delete()
i havent really used this even but i think this should work
yeah so after it gets renamed if its X it will remove
ohh the argument
how can i solve my problem please?
yes, after 30mins the bot should delete the channel #batt-done
@client.event
async def on_guild_channel_update(after):
if channel.name == "test":
await channel.delete()
this?
yeah i forgot
or is it after.name then use the guild to delete
yh
Is this problem the indents to?
https://cdn.drijon.tk/chrome_p9kLRBuGi5.png
oh okay
Anyone knows why this is not working?
if message.content == f"<@{client.user.id}>":
await message.channel.send("Hello", reference = message)
The bot does not send the text when mentioned.
i think its if message.content == (f"<@{client.user.id}>"):
in brackets
@commands.Cog.listener()
async def on_guild_channel_update(before, after):
if isinstance(after, discord.TextChannel):
if after.name == "batt-done":
asyncio.sleep(5)
await after.delete()```
Channel wasn't deleted. I changed it to 5 to test it
@commands.Cog.listener()
async def on_guild_channel_update(self,before, after):
if isinstance(after, discord.TextChannel):
if after.name == "batt-done":
asyncio.sleep(5)
await after.delete()
it should be self
I don't want to just mention it. I want to make it like if someone says, "Hi @mybot", the bot will reply.
it exactly does that
no
did self, work?
no
import disnake as discord
import asyncio
from disnake.ext import commands
class Tracking(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
if isinstance(after, discord.TextChannel):
if after.name == "batt-done":
asyncio.sleep(5)
await after.delete()
def setup(client):
client.add_cog(Tracking(client))```
@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
if isinstance(after, discord.TextChannel):
if self.after.name == "batt-done":
asyncio.sleep(5)
await self.after.delete()
oh its await asyncio btw
wdym no need to await the sleep
try it on ur main file without the self
ok
i think its the cog issue its not being loaded probably did you try on ready and see if the cog is getting loaded?
@client.event()
TypeError: event() missing 1 required positional argument: 'coro'```
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.
Example of coroutine displaying the current date every second for 5 seconds:
if asyncio.sleep worked without awaiting, that would completely break the purpose of the event loop
?
its event
without ()
no parentheses after event
oh
yeah
still did not work
send the code
can you show the intents you passed to your bot's constructor if you have any?
@client.event
async def on_guild_channel_update(before, after):
print('test')
if isinstance(after, discord.TextChannel):
if after.name == "batt-done":
asyncio.sleep(5)
await after.delete()```
oh
yeah, but its still a possible cause
you need to explicitly declare those though 
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
True
only in certain forks
and dpy
since when
what
dpy 2.0 and <2.0 still assume the default() intents
without turning them on explicitly?
yes, all the non-privileged intents
ah ic
there is a 2.0? i havent used dpy in a while or are they other projects like pycord or sum
uh
did you enable intents
several forks are based off of dpy 2.0/master branch
nah, dpy 2.0 is in its alpha stage, still under dev while all the folks of dpy are based on 2.0 version
from the official dpy team?
?
yes
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
okay
yes it is enabled
on the developer protal to?
no
data = dataz.split(":",1)```
dataz won’t split
only server member intent is enabled
I just enable all intents
yeah thats it
is it printing test?
at least
data = dataz.split(":",1)```
dataz won’t split
assuming you've called requests.Response.json(), it returns a dict object so what is there to split
is it from a request response
Ite rewuesting from api
no
It’s like hello:man
It’s requested from api
And api uses json
I just wanna split man part
try inviting the bot to another server
and your bot is online right
Yes it’s returning dict but it’s not sending ig you could call “combo” to bot
So I’ve got hello:man
what endpoint are you using
A paid one
nope
Paid so so I am not gonna share for obvious reasons
wait so not even discord API we're talking about...
visual studio code
Long story
No I’m not
invite the bot to another server i was having the same issue with the guild not getting triggerd
bot.run-
python main.py
bot.run(token)
bor.run("token")
Are you using bot.run
no client.run
rip
yes
import disnake as discord
from disnake import Intents
import asyncio
from disnake.ext import commands
intents = Intents.default()
intents.members = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print(f"Live: {client.user}")
@client.event
async def on_guild_channel_update(before, after):
print('test')
if isinstance(after, discord.TextChannel):
if after.name == "batt-done":
asyncio.sleep(5)
await after.delete()```
regardless their documentation should explain how the response looks like for the API endpoint you've requested, and if not you can just print the json response and figure out how to index the value you're looking for
yes
disnake as discord 
disnake.on_guild_channel_update(before, after)```
Called whenever a guild channel is updated. e.g. changed name, topic, permissions.
This requires [`Intents.guilds`](https://docs.disnake.dev/en/latest/api.html#disnake.Intents.guilds "disnake.Intents.guilds") to be enabled.
dude try the bot on a new server
for your purpose of deleting a channel on rename, reacting to an event is much more responsive/efficient than running a loop
How do I set this datetime to a UTC Timezone? date = datetime(year=year, month=month, day=day, hour=hour, minute=minute)
kkty
whats a fold
So... I want the bot to automatically delete a channel when it is renamed to a specific name (#batt-done or #am-done). Then there will be a log channel which once the channel is delete, the bot will edit its message or embed (log) to Battbattling - 1. So each time the channel is deleted it will be logged in the log channel which the number keeps increasing
its for dealing with ambiguous times
timezones are a bitch
ok i have no idea whaat that is so imma ignore it
ah timezones ok so thats like -6 or +2
indeed
i believe the python docs mentions an example of ambiguity with timezones
ok
can someone send the discord doc or something on timestamps
like <t:123123123132>
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...
if its not being printed then the problem is py @client.event async def on_guild_channel_update(before, after):
thats not the problem
man
it is because it is not being printed
import disnake as discord
from disnake import Intents
import asyncio
from disnake.ext import commands
intents = Intents.default()
intents.members = True
intents.guilds = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print(f"Live: {client.user}")
@client.event
async def on_guild_channel_update(before, after):
print('test')
if isinstance(after, discord.TextChannel):
if after.name == "batt-done":
asyncio.sleep(5)
await after.delete()
client.run("")```
this is everything
did you enable the bot scope when you invited your bot?
do I have to update after the bot is running
so it wont work if the channel is already renamed?
Are the intents enabled to developer portal also?
yeah
a misunderstanding of how events work
Lol
i didnt scroll the entire docs for this 
well... That was the problem 😁
in practical usage you'd manage this by doing a check on bot startup
also py RuntimeWarning: coroutine 'sleep' was never awaited asyncio.sleep(5)
Wait I didn't get it how did the event work?
it only fires when a channel is updated
alright
issue here was that they... didnt update it
Oh
if after.name == "batt-done":```
I want to fit in multiple channel names
how would I do that
multiple string comparisons, either py if name == 'a' or name == 'b': or more preferably py if name in ('a', 'b'):
How do I find the user Id of someone who reacted a certain reaction to a message?
given by the on_reaction_add event or just checking a message?
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
I want my bot to check for reactions on messages in a certain channel on ready
That really sucks lol
no in the developer portal
you'd go through Message.reactions, get the Reaction object you're looking for, and use async for user in reaction.users(): to yield every User that provided that reaction
or .flatten() if you wanted a list
i think he means the dev docs
😩
I don't know I remembed seeing something like that but I cant find it
Yes also heroku isn't a good hosting service
is there any way to host my bot for free lifetime ?👉 👈
or is there something related to %d or smth
yes
basically the same documentation as format_dt
There are no free reliable hosts
you can host on a vps for cheap. If you want free get and old pc and host there
google cloud but you will need a cc they wont charge.
oh okay...
ahhh i don't have a cc
then replit is the only choice for u bud
or a pc that is laying around
i'll try replit
okay
That also doesn't mean replit would be good for you. Wou would face latency issues
or disconnection from discord, when other bots on the same datacenter send too many API requests
Nichijou
is there a way to make a timeout limit for a specifc command function, i found something working with python in general but since discord bots are dealing with async def it cant be called
yes
!d discord.ext.commands.Cooldown
class discord.ext.commands.Cooldown(rate, per)```
Represents a cooldown for a command.
How do Mee6 n other big bot's hold so many configurations for other servers? They are certainly not using Json.. right?
No why'd they
no reason
will aiosqlite going to burn out or what
Hello, I have an error and I don't know how to solve it, can someone help me please?
dont name your file discord.py, as it conflicts with the name of the installed package
burn out as in it starts becoming a bottleneck? afaik you should consider a client-server db once you start doing a lot of concurrent reading/writing in your bot
sqlite's default mode uses a rollback journal which is less efficient for concurrency, but you can change it to a write-ahead log using PRAGMA journal_mode = WAL; which improves performance and i believe avoids database is locked errors (https://sqlite.org/wal.html) (the asqlite library by Danny turns this on automatically)
now I have this error normal?
Exception has occurred: PrivilegedIntentsRequired
Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
During handling of the above exception, another exception occurred:
During handling of the above exception, another exception occurred:
File "D:\Hack\Visual studio code\lrd.py", line 187, in <module>
client.run("TOKEN")
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
of course instead of TOKEN I have the token of my bot
well its telling you what to do
members, presences, and message_content are privileged intents
what a privilege ?
privileged intents have to also be turned on in discord's website
if you click the Bot tab in your application and scroll down you'll see them there
indeed I have activated everything and it seems to work thank you very much however I had tried just before
thanks !!!
my bot does not appear online even though it is start
ok so now, How would I make the bot update logs anytime the channel (ticket) is deleted
you'd get the log channel and send a message to it
if self was a variable that contained an instance of discord.Client sure
but you defined client = commands.Bot() earlier so you probably mean client.get_channel(id)
or self.client if you defined it in a cog...
yes in cog
Why is my bot not saying This cant be blank silly. if he didnt put a nickname after the mention?
(..,nick=None)
nick can't be None indeed
put that in the param
thanks that worked
yeah your nick parameter needs a default value, otherwise dpy will raise MissingRequiredArgument if the user doesnt type it
or maybe it can cuz it's a kwarg
seems like his command got to the embed part anyways
@commands.Cog.listener()
async def on_guild_channel_update(self, before, after):
if isinstance(after, discord.TextChannel):
if after.name in ["batt-done", "am-done"]:
await asyncio.sleep(5)
await after.delete()
log = self.client.get_channel(957281408924139601)
await log.send("Tracking\n\n `BattBattling` - `0`")```
i dont see them implying that
could very well be that the error was suppressed by an improper on_command_error
yeah that seems about right
Is there an param option for get_channel(name=X)?
no
get_channel is only used with IDs
looking up by name would be done with discord.utils.get or similar
Can u use discord.utils.get
no, it is the log channel
I thought u wanted it by name not by id
log is a static channel for sure
when someone renames random channel to batt-done it will be deleted and be logged +1 in log channel. so the bot will edit it to BattBattling - 1 and goes on
oh, im done with that
Is it only for ur sever
yes
Oh okay
so now how would I do this
not only batt-done I plan on making other in the logs different user
well since you need to track that count across restarts, you need some form of data persistency
if you have a database then you'd store the count in that
but it should be edited in the log
yeah an alternative could be having one message that stores the count, then every time you start your bot you'd fetch that message to retrieve the current count
so I need a database uh
which database
i see people json
they say its simple to use
Json isn't a database
i would suggest something SQL-based since if you decide to add more features like inventories or currency, SQL will be really suited for that kind of consistent format
And it's definitely not simple to use
ok, but it stores how exactly would it edit its message
SQLite via the asqlite or aiosqlite library is a good place to start since its all stored in one file
also would I need to worry about this event crashing with othee events/commands
you store just the channel and message id, which is all you need to edit it
depends on what it does but so far it seems pretty isolated
what of in logs will it edit there as well
wym
would it add the +1 in the log channel
not by itself, you need to create the new message somehow
hence why you'd use a database to store the count
hello I have this error: Exception has occurred:
ModuleNotFoundError No module named 'discord'
can help me please?
pip install discord.py
why dont you tell people to install 2.0 😔
an example of editing would look like this ```py
channel = bot.get_channel(343944376055103488)
partial_message = channel.get_partial_message(957288134037602324)
You could use await channel.fetch_message() to get a Message object from discord,
but when you only need to edit you can use a partial message instead
await partial_message.edit(content='new')```
ok
hi guys i have this problem
@bot.command(pass_context=True)
async def embed(ctx):
embed = discord.Embed(title="Titulo", description="Descripcion", color=0xffffff)
embed.set_footer(text="sub-texto")
embed.add_field(name="info1", value="Hola", inline=True)
embed.add_field(name="info2", value="Chao", inline=True)
await ctx.send(embed=embed)
I wrote this code but it gives me an error
File "main.py" , line 15
await ctx.send(embed=embed)
^
syntaxerror : "await" outside function
those last four lines arent indented in your command
so how do i solve it :,,v ?
thks bro
... indent them inside your command
ok
Too much work to type in the whole fricking url
well
if you search up dpy documentation it defaults to the stable branch so you'd have to mention that caveat too
uh yeh
Indent it
how xd ?
Press space 4 times
ok
You can also press the TAB key in most editors. Which one do you use?
pep8 compliance officer didn't say tab cuz he's pep8 compliance officer
visual studio
Visual studio code
Yeah then you can press the TAB key above Caps Lock to the left to indent.
ok
Hey, I'm using discord_slash and I'm having trouble with reacting when users pick an option of a select, the event is simply not firing, am I maybe waiting for the wrong one?
It never prints success?
yes
when I change the event to typing and start typing it fires tho (and prints success)
Have you waited for interactions previously? As in, are you sure that interaction_create is the right name?
Which version of discord.py are you using this with?
Pretty sure it’s on_interaction
you can someone help me im using disnake api,
class MyModal(disnake.ui.Modal):
def __init__(self) -> None:
components = [
disnake.ui.TextInput(
label="Name",
placeholder="The name of the tag",
custom_id="name",
style=disnake.TextInputStyle.short,
max_length=50,
),
]
super().__init__(title="Moderator Application", custom_id="ModApp", components=components)
async def callback(self, interaction: disnake.ModalInteraction) -> None:
embed = disnake.Embed(
title=f"New Mod Application",
description=f"<@{interaction.author.id}> Submitted This Application ",
color=0xDC143C
)
await interaction.response.send_message(embed=embed)
async def on_error(self, error: Exception, inter: disnake.ModalInteraction) -> None:
await inter.response.send_message("Something Went Wrong Here...", ephemeral=True)
this is my code, if anyone knows how, can you help me pull the name from this, i cant figure it out
Isnt working either
discord_py_slash_command-3.0.3
i just learned about modals today, and the example code is confusing me a lot
how to play an audio file with my bot?
you cant strait play a audio file you need certain librarys
I mean with ffmpeg
I'm trying to get my bot to display a photo in discord but when I give the command my bot returns "<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=1000x983 at 0x202DBEAAB90>"
Any idea how i can get my bot to display the actual image instead of the data?
Show how you send it
name?
Somebody help ^^^
ask in #python-discussion not to be rude or anything
it is a discord.py error
i recommend sending users to #❓|how-to-get-help, not python-general
@boreal ravine
pygen move quite fast. an individual help channel is the appropriate spot to get help for things like this
users is empty ig
Yeah change it to event='interaction'
hmm i reacted so how empty?
try printing users
okay
ok
I did, didn't work either
worked thnks @boreal ravine
This may be helpful https://discordpy.readthedocs.io/en/stable/faq.html#how-do-i-upload-an-image
Ty
client = discord.Client()
player1 = 0
player2 = 0
playerOneIn = False
@client.event
async def on_message(message):
messageContent = message.content.casefold()
guildChannel = message.channel
if message.content.startswith('hm!player1'):
playerOneIn = True
player1 = message.author.id
print(player1)
await guildChannel.send(f'<@!{player1}>, wait for Player 2 to use `hm!player2`.')
elif message.content.startswith('hm!player2'):
print(player1)
if message.author.id == player1:
await guildChannel.send(f'<@!{player1}>, you are already playing as Player 1!')
How do I make it remember player1 variable?
what do you mean by remember?
it looks fine
compare it then? 
But for the first print(player1), it prints user's id, and for the second, it prints 0
So it doesn't remember it
got it working!!! lets gooooooo
thanks again
is there a list or some docs somewhere that i can reference?
it should've worked, did you restart your bot between the first and second time?
1.7.3 I think
Nope
Somehow doesn't work
hey, I have a question, in discord.py I imported another file to generate a random room in 2D using recursive generation the thing is, the function in the other file returns a string so I only had to call the function from the command and send the output, but it is giving me an error and I can not find any info about it
await ctx.send(room.room(int(x),int(y))) AttributeError: 'Command' object has no attribute 'room'
Thanks, but I don't see an interaction event 🤔
Did you name your function room?
lol, found it after opening the discord_slash docs in wayback machine 😂
is it like this?
nope Cogs are a subclass of Cog hence the usage of self and the Cog.listener() decorator
oh yea sorry forgot to change that
I think it should be if [val] in after.name
alr so now im still confused how I am going to make the logging
thats what exenifix told me
he said its correct
Did u try it at least
Then it should be await log.send()
no not like that
what is val?
hold on real quick
@slate swan
so if another channel batt-done is renamed it will be deleted, and the message in the log channel will be edited to BattBattling - 2
if ["list", "of", "a", "string"] in "string":
is what youre given which is wrong. and would raise a left operand error
so each channel with the name batt-done will be deleted and keeps adding to the log
Oh yeah mb
!d discord.Guilds.channels
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
just iterate through the list
for channel in ctx.guild.channels:
if channel.name == "":
...
something like this
?
bro you want to find all channels in a guild which such name right?
yes, I am already done with that
Im talking about logging it
logging as sending actions to another channel?
or a tracker
no
I dont get it just send it to the logging channel
ah I wish i had an example of what i am trying to do but they kicked me from the server
yeah as said you have gotten the channel obj from cache?
well, when someone renames the channel to batt-done it will be deleted and be logged +1 in log channel. so the bot will edit it to BattBattling - 1 and goes on
so it will be BattBattling - 1
if another channel renames and get deleted with the same name it will be BattBattling - 2
and keeps on going
more like a tracker than logging
then just look for 2 names and set values to variables?
So if u rename a channel it will be deleted and named to bat-2
yes and if another bat -3
2 names?
not sure what you want as the explanation isnt quite clear
Hmm u could use +=1 but if u rerun it will start over again using something like a json file will help u keep track of the number of channels
no
But i dont get why u r doing this ur the owner and only mods can change the channel name whats the point
just use aiosqlite as youre using it in your bot
Ye that too
Oh ok uhm
What r u making like a ticket bot?
Or what is this
Cuz i dont get why u or anyone would rename a channel for it to be removed and then create a channel called BattBattling - X
When someone renames a random channel to batt-done it will be deleted. Then in the log channel there will be a message BattBattling - 0 it will be then edited to BattBattling - 1 and if another channel renamed to batt-done gets deleted and then BattBattling - 2 and keeps on going
Reasons. Its a ticket system. So if i want to check on how active my staffs are doing the tickets there be a tracker for it
Just send the logs to a channel that only u can see no need to edit so use aiosqlite to keep track of how many channels u made then send the data to ur logs channel
Im using json to store my ticket system stuff😅 😅 🥲 🥲 🥲
Yea but they are reasons of why I am doing it
Okay
Can anyone suggest me any simple db for dc bot
So back to it, since we are done with the delete, I should make a database for the log?
sql, for a file sqlite and use the aiosqlite bridge if a server postgresql and use its async bridge asyncpg
i sent it earlier
i dont know what to do next
how I am supposed to get the user
Wdym by "for a file"
the data gets stored in a type db file
Hi
and ofc you meed to know SQL
Lol then ill learn sql first
um.
most people cant afford a server to host there pg server and sqlites only down side is it gets stored in a file so its not the best for big bots like mee6 but if the bot was big then yes pg should be your choice as some companies use it as well.
dont you have to host the server?
...
then how the heck would you access the db does it localhost?
yeah true
+im new to db stuff
what makes pg hard its queries ive heard theyre a bit difficult?
I mean on a vps it can be self hosted.
It's SQL everything is the same..?
ik but ive heard they had changed some stuff on it im not sure
In PG it's just easier to go more advanced but you don't need to if you don't want to.
I use it, not that I know of then.
mhm thats nice
I mean yeah ofc.
But if your bot isn't as big as groovy you won't need a separate database host.
over how many guilds should you be considering switching from SQL?
pardon? and its not depending on guilds it depends on how much data you store and how many queries you make so how much tasks it would be given
im a beginner and sqlite is giving me headache
why?
I was storing a large about in a json object thats why i thought to shift to db
it's pretty straightforward
its pretty easy its docs are good and all you need to learn is sql
Lol

how am I supposed to know it was after the bot was running no one told me
well its not often someone assumes that an event can trigger while the bot is offline
def can_execute_action(ctx, user, target):
return user.id == ctx.bot.owner_id or \
user == ctx.guild.owner or \
user.top_role > target.top_role
what do the \ do here?
line continuation character, it just lets you write a long expression across multiple lines
as in manually making a request to discord?
oh i see thank you
if its part of your discord bot you can use the internal HTTPClient and Route class to make the request, that way dpy handles the authorization and ratelimiting for you
its internal
you'd have to figure it out from the source code and its usage in other dpy methods
yes
Can't do that
Name the function something else and use the name kwarg in the command decorator
an example usage would look like this py route = discord.http.Route('POST', '/channels/{channel_id}/messages', channel_id=343944376055103488) payload = {'content': 'my message'} await bot.http.request(route, json=payload)
!d discord.ext.commands.Bot.command
@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
ok let me try it, thx
or at least thats what i did once last year to try out the voice activities which weren't yet public
i want to make my discord bot have a command where it sends ur message embedded
@commands.command()
async def embed(self, ctx):
msg = discord.Embed(
title='message',
description=msg,
colour=0xffffff,
)
await ctx.send(embed=msg)``` something like this but idk how to do it
!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.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
why are you putting the embed instance as the description??
the description should be whatever the user says
for example, ?embed hello
then the bot sends hello embeded
put message as an argument to the function and put description=message
how do i read the message history of a channel with a bot if i just give the bot an id
@commands.command()
async def embed(self, ctx, message):
embed = discord.Embed(
title='message',
description=message,
colour=0xffffff,
)
await ctx.send(embed=embed)``` so like this?
yes
the channel
id of a channel?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
it works but it breaks when a space is added in the message
how do i fix that
async def embed(self, ctx, *, message)
hey guys i have problem my problem ```py
with open("data.json") as file:
data = json.load(file)
error SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
Check your data.json, probably some unicode emoji inside
now_utc = datetime.now(timezone('UTC'))
await bot.say (now_utc.strftime(fmt) + " (UTC)")``` why does bot error?
bot underline
nvm i figured it out
bot.say is old
its been changed
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Hi, how can i get channel from ID?
tried py self.client.fetch_channel and self.client.get_channel but none of those worked
yep i should have
on the developportal all of the three
Are you passing an ID like 123 or "123"?
yep 😄
infochannel = self.client.get_channel(id) and infochannel = await self.client.fetch_channel(id)
i tried both of them (not at the same time)
And still got ```AttributeError: 'NoneType' object has no attribute 'send'
Ok, the "123" is wrong, you only use 123 as IDs are integers
And in what cases are you getting the channel from?
i know that
Is it in a command, etc?
in task loop
Ok, there is your issue then
A tasks.loop starts before the cache is populated
You would need to use wait_until_ready in your task
!d discord.ext.commands.Bot.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the client’s internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.setup_hook "discord.ext.commands.Bot.setup_hook") can lead to a deadlock.
I have that
Call & await this, afterwards grab from cache
Can you show your code then?
Does anybody know how to fix this ? ```@client.command()
async def clear(ctx, nombre : int):
messages = await ctx.channel.history(limit = nombre + 1).flatten()
for message in messages:
await message.delete()
def __init__(self, client):
self.client = client
self.send_shop_all.start()
@tasks.loop(seconds=50)
async def send_shop_all(self):
check_time = datetime.datetime.now()
channel = 945075687000272926
infochannel = await self.client.fetch_channel(945075687000272926)
if check_time.hour == 18 and check_time.minute == 37:
some code here....
@send_shop_all.before_loop
async def before_shop_all(self):
await self.client.wait_until_ready()
here
This should be working fine, perhaps try getting rid of the before_loop hook, and calling & awaiting self.client.wait_until_ready directly in send_shop_all
w8 im stupid, I mixed the ids....
Fuuuuuu me xD
lmao
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this...
There are some examples in the docs above
sorry for that
Can you give examples of what you mean?
What do you mean different classes?
But you want to reset permissions only when close right?
So you can put it under the class CloseTicket class
Can you give your current code for the CloseTicket class? @slate swan
how do i get my bot to send a message to a user when given the user's id
!d discord.Member.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
Is this a command?
no
Then?
well it is reading a chat history and sending a dm to all users who said a certain keyword
So isn't this a command?
wdym by command
Are you doing DMing users within a command?
@bot.command()
no
Do you restart the bot often to do what you're doing?
yes
But you're deleting the channel so do you need to change channel permissions?
if you say so
I would personally suggest not changing it, because the channel is going to be deleted but it would be like this
await ctx.channel.set_permissions(ctx.guild.default_role, read_messages=False)
ctx.guild.default_role is the @everyone role
!d discord.Guild.default_role
property default_role```
Gets the @everyone role that all members have by default.
it will set the View Channel permission for the @everyone role to False
it doesn't delete any overides, it just changes it
you can delete overwrites too if you want though
are you an admin?
that permission is for you
not the @everyone role
how can i make it so it says like 5th or 2nd or 3rd
Someone who can help me with discord bot requirements? tag me when anser. Thanks
like j the letters after it
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
that is an inefficient way to do this.
Consider using this.
@nextcord.ui.button(label="Yes", style=nextcord.ButtonStyle.green)
async def accept(self, button: nextcord.ui.Button, interaction: nextcord.Interaction):
seconds = 10
msg = await ctx.send(embed=disnake.Embed(description=f'The channel will close in `{seconds}` seconds'))
while seconds > 0:
print(t)
seconds -= 1
await asyncio.sleep(1)
await msg.edit(embed=disnake.Embed(description=f'The channel will close in `{seconds}` seconds'))
await interaction.channel.delete()
self.stop()
is there anyway to change ip of replit?
Nope
Ummm I was working on a new help command that uses the class but it sends 4 times why?
yeah just kill the terminal
i tried that before you say
i changed the project name and it worked
everytime you get a new terminal afaik it changes the ip so you probably got a different ip
you'd have to do it with if statements checking the last character
kill 1
in the shell
right right
whatever it was, its fixed now
and
i think i know why ive got that 429error
def retrive():
global channel_id
req = requests.get(url + '?limit=1',headers = header)
for value in json.loads(req.text):
#print(value['author']['id'])
if value['author']['id'] == '701802881962999918':
if value['content'] == "$hourly":
hourly()
if value['content'] == "$giveaway":
others(cmd='comfirmed!', iurl= url)
giveaway()
if value['content'] == "$online":
others(cmd= 'bot is online', iurl= url)
if value['content'] == "$uptime":
others(cmd= time.process_time() - start,iurl = url)
if value['content'] == "$bcc":
bcc()
if value['content'] == "$rob":
rob()
if value['content'] == "$cnlid":
others(cmd= f'act channel is {channel_id}',iurl= url)
if value['content'][0:7] == "$setcnl":
channel_id = value['content'][8:]
requests.post(url, data={"content":'confirmed!'}, headers = header)
genurl()
#hourly()
#schedules
#schedule.every(5).seconds.do(others, cmd='ridan')
#schedule.every(70).seconds.do(others,cmd='!afzaiesh')
#schedule.every(2).seconds.do(retrive)
schedule.every(11).minutes.do(rob)
schedule.every(61).minutes.do(hourly)
schedule.every(61).minutes.do(giveaway)
schedule.every(13).hours.do(others, cmd='!kheirie', iurl=url)
#------------others-----------------#
schedule.every(10).minutes.do(bcc)
#inf-loop
while True:
schedule.run_pending()
time.sleep(1)#second counter
except Exception as e:
print(e,'error occured')
others(cmd=e,iurl=url)
raise
it was the only way that i could think about
and the reason i got rate limited
how i can send data to server?
in a cleaner way
Ummm I was working on a new help command that uses the class but it sends 4 times why? And it is the one from the pin
sends 4 times what?
It sends the help 4 times
Using that directly
hi guys Im searching for a program to add a role when a user has a certain custom statut, there are a lot of tutos on js but not on python... thank you
!d discord.Member.activity
property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
!d discord.CustomActivity
class discord.CustomActivity(name, *, emoji=None, **extra)```
Represents a Custom activity from Discord.
x == y Checks if two activities are equal.
x != y Checks if two activities are not equal.
hash(x) Returns the activity’s hash.
str(x) Returns the custom status text.
New in version 1.3.
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
oh thank you so much appreciate it
All cool
Can you explain why my help command is going nuts? #discord-bots message
I just made a bot that sends random monkey images every minute.
@echo wasp code
It s that gist link
thats cursed and time wasting cool
ahhh
wrong rply
4 times......?
It is not cursed
Oh wow what a coincidence
ditto same code?
Lol not the top part
See? the bot is too uwu to function properly
I, uhhhh
monkeys but not pandas??
Lmao
mina, u didn't get it. The bot scrapes NFT websites and sends those after processing and seeing if they are monkey NFTs
aleifht
take this to an ot channel
smh I will just go away finalizing sound effects
good good
I know it's not ctx, but what is it then?
Still says wrong when I do guild.member_count
try doing member.guild.member_count
does discord.Reaction.me check if it was the bot that added the emoji?
Looks good. Ill test it out, thanks.
If the user sent this reaction.
I think so, not 100% sure though
I would test it yourself first
xd
t!profile
fire
you drew it ?
yes, am not much of an artist but i tried
Wait you are right :(
A friend of mine requested monke
disnake still
i started on disnake and tried to move to dpy today
i've not figured out the slash commands and stuff
That's okay, starting off without slash commands is better tbh
I still firmly believe that slash commands was a mistake
lolol, how come?
discord says it's made to be easier for the regular user, but that is barely true. At least with all the rules it has
And my main point would be the power that regular "commands" have
idk if it's in my head but every bot i've used with slash commands there's like the slighest of delays/lag
Slash commands just aren't ready yet
This is a activity command once you know how to make commands and know data types this shouldn't be too hard to get into ```py
@slash_command(name="activity")
async def together_activity(
self, inter: ApplicationCommandInteraction,
channel: VoiceChannel,
activity: str = Param(choices=list(together_apps.keys()))
) -> Message:
i got lost with the "trees" and syncing
typing.Annotated```
Sync isn't something I worry about rn, I recommend to just put it in test mode.
can i do that in dpy?
I think "tree" is sort of misleading
It's more like a list than anything
Not sure, i haven't really looked at dpy slash command implementation since it's fairly new and no one has asked. Dpy is just a bit behind Disnake atm.
I've done a slash commands with d.py, none with the forks so I can't really tell if it's behind :p
are there any more comprehensive guides to slash commands for dpy yet?
No unfortunately. I've had to go off of the gist which was sorely lacking. I've made a modal example and the "docs team" if you can call us that are working on it
yeah.. saw those gists lol
2.0 docs does have the classes, attributes, functions, etc but no real examples or explanations as to why and how one should use it
why is my buttons not being send?
@Client.command()
async def button(ctx):
await ctx.send(
"",
components = [
Button(style=ButtonStyle.red, label = 'test!')
]
)
interaction = await Client.wait_for("button_click", check=lambda i: i.component.label.startswith(""))
await interaction.respond(content="test")```
source dive
Yeah that was one of my strategies on working up some examples, but I don't think many people would want to source dive just to figure out how something works
tbh i wouldn't change to dpy. danny archived the repo and then criticized forks for there implementation or making dpy "worst" and then saying he didnt like them but it was mainly his fault for leaving the community like that, he said he tried to find a maintaner but never found one i find that very weird in my part and then he came back after 6 months of chaos, while forks will continue development, which in my part i dont trust danny maintaining the lib anymore, why exactly? he sent many gists on how he maybe wouldnt comeback because he didnt had the time etc but then after 6 months he sent a gist going against all his claims before that and i wouldnt doubt the lib being archived again.
yeah i'm aware of all the backstory
none of my discord bot writing is for any real use
you say that after you stopped maintaining rin
just for fun/learning and no one is gonna use it
The timing for the disnake port was crazy though lmao
yes lol
I'll maintain if I feel like
but if I start it again, I'll b starting from scratch
This time I'll do some websockets with TCP or something
(Yea, I know, crazy)
its discord bots at the end of the day most devs do this for fun
which line
I'll prob do a danny and comeback in 6 months
and then leave it again
@Client.command()
async def button(ctx):
await ctx.send(
"",
components = [
Button(style=ButtonStyle.red, label = 'test!')
]
)
interaction = await Client.wait_for("button_click", check=lambda i: i.component.label.startswith(""))
await response.send_message('Hello')```
like this?
why not use main or a fork and not that trash third party lib
i hate how you have to wait for a button click in that trash lib
i dont know what your meaning, im trying my best!
Probably
e
ill do a bad implementation myself
still doent send
btw andy do you use keepalive like all dpy forks?
for websockets?
No lol that's old asf
what do you use aiohttps websocket support or httpx?
alright ill look into it
keepalive is simply for sending heartbeats
what? really?
Making a thread like that is kind of just useless, you can get rid of it and make a task
ah so you cant make a handshake with it?
You connect with aiohttp, send your identify payload with your authorisation data
and connect to the websocket?
Hearbeats just let the gateway know your are still there
You connect with aiohttp
yeah ik
nvm that
anyways ima watch the new batman movie see ya thx andy
mid
doubt
aiohttp supports websockets?
!d aiohttp.ws_connect
!d aiohttp.ClientSession.ws_connect
coroutine async-with ws_connect(url, *, method='GET', protocols=(), timeout=10.0, receive_timeout=None, auth=None, autoclose=True, autoping=True, heartbeat=None, origin=None, ...)```
Create a websocket connection. Returns a [`ClientWebSocketResponse`](https://aiohttp.readthedocs.io/en/stable/client_reference.html#aiohttp.ClientWebSocketResponse "aiohttp.ClientWebSocketResponse") object.
yeah
why it doesn't work ?
Oh cool, didn't know that was a thing
It's bot.command()
Client has no sense for a "command". If you have a commands.Bot named as client, you should change it
oh yeha
i'm stupid my bad
still doesn't work
ohhh
wait
type hint amount to an int
so amount: int = 10
you mean I should change client.command() to bot.command() @sick birch?
he means to rename your bot instance yes
but rn thats not the problem its just naming
still doesn't work, here's the code
still doesn't work*
Yes but make sure your bot instance is also called "bot"
show code
Ah your on_message
You need to:
A) Use a listener as opposed to an event
B) Append bot.process_commands(message) to your on_message
Also you shouldn't be changing presence in on_ready
they should remove event deco tbh
rather pass it on to your bot instance
Nah, on message event can be useful
how exactly?
Ignoring certain users, channels, guilds, etc
I know they can be done with a check but having multiple ways is always nice
which line
listeners are better than events imo
Ah well for the "features" i mentioned above we need an on_message event
I'm not just going to tell you what to change and at exactly which line that won't help you
yes but the message event can still be decorated with a listener
Yes, but then you can't really ignore certain commands
which you can set a name as well
Using listeners I mean
@bot.event
async def on_message(m):
if m.author.bot: return
await bot.process_commands(m)
for example
That's not really possible with a listener
Refer to the 2 options I provided above
well you can just return the function in that case
Both will work
Return which function?
nah nvm that i didnt quite see the return statement
and why have an extra line which is taken by a useless coroutine?
you need to await process_commands
Yeah true, a check works as well
oop
!d discord.ext.commands.Bot.listen | just use this
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
and remove process commands coro
I don't understand why you guys are changing this if its working
it will make >clear work )
this was a pain in the ass to get working right
looks good : )
thanks, just gotta get it to save properly now
maybe change the text color so it doesn't clash with the gui
it makes things better
not bad i like it
i just thought of another thing i need to add, i swear this bot will never be done
that's the good part!
what the f!
you process commands lots of time with this
because of the for loop
or sometimes you don't even process commands
so that's why okimii told u to use listen() instead
but idk where to add listen()
How do you make a command like .steal
, if you do a emoji from a other server that it will 'steal' the emoji and add it
I just didn't look at the picture again
replace @bot.event with @bot.listen()
smth like this
like that
it will make my clear command work ?
yes
because it doesn't override the default on_message now
the default on_message in the src code which calls your commands stays and does its work
😀
no I'm meh
I'VE BEEN STUCK FOR HOURS ON THIS
feels great to finally solve it innit
int(guild_rank[player.guild][2].split(f",{buid}")[-2].split(f"/{buid}")[1])```
you ever just look at some pieces of dumb code and
you split by a whole var
is buid a sentence
it would be really cool if buid was like a damn whole sentence
I can again
buid is 4 unique characters 😓
the whole thing gets one number as a result that's either 0,1,2
it works though so im never touching it again
YES, BECAUSE IT MEANS THAT EVERY NEW SCRIPT WILL WORK
not sure how as me and robin helped you lmao
skill gap
bruh I forgot a ","
now imagine it will not work later even if you don't touch it again
tiens un français 🙂
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
man he is french like me...
🗿 bro i don't like french
idc
ban
ok
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
can you guys stop?
sure
how rule 4 applies on my message 🗿 man shut up pls before i start saying something bad about french people
please dont be rude.

hey @slate swan considering this code what would be the best way to figure out what button was pressed? ```py
for i in range(3):
for j in range(3):
v.add_item(item=buttons[i][j])
await ctx.send(view=v)
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overridden by subclasses.
ouii
and when does an interaction happen? Do i have to wait for some kind of interaction?
Subclass discord.ui.Button and override the callback coro
An interaction happens when a user clicks a button, runs a slash command, context menu, submits a modal, etc
im getting error: Command raised an exception: TypeError: string indices must be integers
so do you have to wait for an interaction after sending buttons?
with some function or something
data = req.json()
manz = '\n'.join([result['checks'] for result in data['limits']])
await ctx.send(int(manz))```
im getting error: Command raised an exception: TypeError: string indices must be integers
what is result and data
],
"limits":{
"checks":999997,
"keyword":999999
}
}
result["limits"]["checks"] isnt it?
doesn't seem like your obj structure matches what you are trying to do
wdym
i'm guessing that that whole dict or whatever structure it is is named data
yes
lemme test somethng rq
!e
a = {
"foo": {
"bar": "baz",
"other": "other2"
}
}
print([v["bar"] for v in a["foo"]])
@slim ibex :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 8, in <module>
003 | File "<string>", line 8, in <listcomp>
004 | TypeError: string indices must be integers
ok so
Well yes, but discord.py handles this for you
so the issue is with result["checks"]
!e
a = {
"foo": {
"bar": "baz",
"other": "other2"
}
}
print([k for k in a["foo"]])
@slim ibex :white_check_mark: Your eval job has completed with return code 0.
['bar', 'other']
so do i basically just do interaction = discord.ui.Interaction after sending the view?
i need bar tho
the value of it?
ok
the 85843 is what i need
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['baz', 'other2']
do u not need int
?
nvm
you were trying to slice the expression in the list comp
!e
py "limits": { "checks":999997, "keyword":999999 } } print([v for v in limits["checks"].values()])
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | "limits": {
003 | ^^^^^^^^
004 | SyntaxError: illegal target for annotation
o mb
!e
"limits": {
"checks":999997,
"keyword":999999
}
}
print([v for v in limits["checks"].values()])
@slate swan :x: Your eval job has completed with return code 1.
001 | File "<string>", line 1
002 | "limits": {
003 | ^^^^^^^^
004 | SyntaxError: illegal target for annotation
lol





