#discord-bots
1 messages Β· Page 45 of 1
can you help me with a error
Event loop is closed isnt an error you have to worry about
its just a bug with the ProactorEventLoop that windows uses
then how do I get my bot to go online
is there a different error in your terminal when you scroll it up?
there's your token, reset it on discord developer site
and enable all the privileged intents within that same bot page
I did bro
works now
@client.command()
@commands.has_permissions(manage_messages=True)
async def temp(ctx, level):
async with client.db.cursor() as cursor:
await cursor.execute("DELETE FROM levelSettings WHERE guild = ? and levelSettings = ?", (ctx.guild.id, level,))
await client.db.commit()
await ctx.send("Removed the level")
``` just trying to make a temp command so I can do ``.temp 1` (1 would be the level whereyou would get x role what says None) and it would remove that but this is not working either
well what did you name the third column that stores the role's level?
from discord.ext import commands
bot = commands.Bot(command_prefix=",",intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is online")
@bot.event()
async def ping(ctx):
await ctx.send("pong")```
do i change to client.event
how can i make a reminder command without using sleep? sounds too lazy just sleep for a time
uh not too sure tbf this was the insert command
@client.command(aliases=["sr", "addrole"])
@commands.has_permissions(manage_messages=True)
async def setrole(ctx, level: int, *, role: discord.Role):
async with client.db.cursor() as cursor:
await cursor.execute("SELECT role FROM levelSettings WHERE role = ? AND guild = ?", (role.id, ctx.guild.id,))
roleTF = await cursor.fetchone()
if roleTF:
return await ctx.send("A role or level setting for that value already exists")
await cursor.execute("INSERT INTO levelSettings VALUES (?, ?, ?, ?)", (True, role.id, level, ctx.guild.id,))
await client.db.commit()
await ctx.send("Updated that level role")
what you had the first time with @bot.event is correct
so just do the same thing for your second event
scheduling
yea but why is that an error its stopping me from running the bot | how do i fix?
because you're calling the decorator, and its not meant to be called like that
its like calling an integer, 1(), some things just dont let you do that
surely you remember what columns you had in your levelSettings? id suggest SQLiteStudio if you want a gui program to check
It's levelreq I think
so this ?
await cursor.execute("DELETE FROM levelSettings WHERE guild = ? and levelSettings = ?", (ctx.guild.id, level,))
``` If its `levelreq` what should this be then
from discord.ext import commands
bot = commands.Bot(command_prefix=",",intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot is online")
@bot.event1()
async def ping(ctx):
await ctx.send("pong")
no, just @bot.event
when I do that i get this
@bot.event() is not equal to @bot.event
and ping is not an event
it's a command
so just @bot.event
it should be @bot.command()
yes but ping is not an event, it's a command
you need () here
I store the date in a database and check like every 10 sec if the current date it's equal to the stored one? doesnt sounds correct, since one second of difference would make the times distinct... not sure how to implement that without checking literally every sec
ik
btw the roles list doesn't make sense
yes
you already have interaction.author.roles
it's already a list
Hi could someone help me out with some sample code?
I want to add a reaction to an already sent message but my code doesn't work.
interaction.user.roles return a list of roles
you're iterating the list to create another list
this doesn't make sense coz there's no if statement
you're practically copying the list
yes but it's useless, try to print roles and interaction.user.roles and compare the items
ok
btw what's the problem
is it a error?
uh, I think there's a problem with the sql query
transactionId query is returning None
idk your database, also where should be capitalized WHERE from too FROM
int was not the problem
the problem here is that the sql query is returning None
you need to work on the sql query
!e
print(3**2)
@glad cradle :white_check_mark: Your 3.11 eval job has completed with return code 0.
9
can some one show me how to make a bot
youtube has lots of tutorials
go and watch the newest
all system are on yt
i need to go
sorry i'll help later or ask someone else
Hey @slate swan! 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!
hmm
get token here
https://discord.com/developers/applications
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
ok bye
Hey @slate swan! 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!
i have
the token
alr
Hey @slate swan! 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!
can some one show me on how to make a bot
how can i read messages someone has sent to my bot
async def embed(ctx, member:discord.Member = None):
if member == None:
member = ctx.author
name = member.display_name
pfp = member.display_avatar
embed = discord.Embed(title="This is my embed", description="Its a very cool embed", colour=discord.Colour.random())
embed.set_author(name=f"{name}", url="", icon_url="")
embed.set_thumbnail(url=f"{pfp}")
embed.add_field(name="This is 1 feild", value="This field is just a value")
embed.add_field(name="This is 2 feild", value="This field is inline True", inline=True)
embed.add_field(name="This is 3 feild", value="This field is inline False", inline=False)
embed.add_footer(text=f"{name} Made this Embed")
await ctx.send(embed=embed)```
can someone help me fix this error?
!d discord.Member.guild_avatar
property guild_avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the guild avatar the member has. If unavailable, `None` is returned.
New in version 2.0.
!d discord.Member.default_avatar
property default_avatar```
Equivalent to [`User.default_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.default_avatar "discord.User.default_avatar")
!d discord.Member.avatar any of these work
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
pfp = member.avatar
also member.name is enough (real name)
member.display_name is name in server
he could do pfp = member.avatar if member.avatar else member.default_avatar
member.avatar could be None
pfp = member.avatar or member.default_avatar
does anyone know whats going on
im getting this error when i try to run my discord bot on replit
Traceback (most recent call last):
File "main.py", line 133, in <module>
client = discord.Client()
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
but i have never had this error befor and on my computer it runs fine
!intents are required in 2.0
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.
The reason it works on your computer is because youβre running an old version
oh ok
well the only events i use are on_message and on_ready
lol ive tried reading the docs but my bot still isnt working
i just dont know the names of the intents i want
Try default if youβre not sure
i have but im getting this error from when i try to start my loop
File "main.py", line 1199, in <module>
event_manager.start()
File "/home/runner/minecraft-bot/venv/lib/python3.8/site-packages/discord/ext/tasks/__init__.py", line 398, in start
Press CTRL+C to quit
self._task = asyncio.create_task(self._loop(*args, **kwargs))
File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/asyncio/tasks.py", line 381, in create_task
loop = events.get_running_loop()
RuntimeError: no running event loop
How are you starting the event loop
also for context event_manager is just this
@tasks.loop(seconds=60)
async def event_manager():
#code
event_manager.start()
my goal is to say the word count and itll start listening for a number than add 1 to it
can anyone explain or redirect me to a tutorial
am I allowed to/is it possible to launch 2 bots at once in the same code?
With threading sure, but you may as well just have them as 2 seperate processes
true but they change alot and it gets annoying so i thought same code would be easier for me, thank you though! have any idea how id go around doing it/have any website or doc i can see?
"Change a lot" as in how?
the tokens are reset alot cuz im stupid and gave a friend access to my acc
π€ not sure how having multiple bots on the same file is going to help with that
https://realpython.com/intro-to-python-threading/ pretty good article on threading if you're interested
whenever i regen them it'd be easier putting them in one code rather than finding both in my massive collection of useless codes with my very unorganized files lmao
thank you
I think threading is sort of overkill for this. Just set them as environment variables, or in a seperate configuration file. You shouldn't be hard-coding your token into your files anyway
intents = discord.Intents.default()
intents.messages = True
client = discord.Client(intents=intents)
Ive also taken the neccicary action on the developer portal
My bot is able to come online, but its not responding to any commands :(
Does anyone know what im doing wrong
true but wouldnt learning threading be beneficial in the long run either way?
It's intents.message_content = True
I agree, but you know, just save yourself the headache π
The knowledge would be useful yes, but not when used to answer a problem which doesnt need that sort of complication
Got any errors?
before and after overwrites. Should be channel permissions
haha well ill do that instead (ill make a config file) thank you lol
Nope. It won't print also
on_guild_channel_update
It just won't print once a change is being made to the channel permission lol
Does the event even get called?
haha yes π
Ahahaha yay yet another error :)
Now its saying discord.Member has no attribute avatar_url_as
Is this another intention?
i was just working on other stuff when i noticed in the models of the antinuke that i forgot to add channel perms check.
avatar.url
And i just tried looking thru the docs and stuff but nope
it just won't print
the only parameter for permissions is overwrites
Audit logs are really inconsistent so if there's not a code error there's not much you can do
Yeah i know it takes a few secs before it shows up in the audit
should i try to sleep the event? for a few seconds
then see what it does?
Not just that, some times it won't show up at all
It currently does. I can see that in the audit logs
Okay, looks like you got lucky. I'd suggest put a print statement inside the for loop first to see if the for loop is being called
sure
No that dosent work :(
Im using the avartar in pillow to put in a picture.
discord.Member.avatar_url_as works on my computer, i just need to know what they changed it to lol
So yeah uhm
fuck π
!d discord.Asset see the methods here
class discord.Asset```
Represents a CDN asset on Discord.
str(x) Returns the URL of the CDN asset.
len(x) Returns the length of the CDN assetβs URL.
x == y Checks if the asset is equal to another asset.
x != y Checks if the asset is not equal to another asset.
hash(x) Returns the hash of the asset.
Strangley using what you gave me dosent return errors but also no results lol
what the fuck wait
oh wait
Okay so robin the issue is not how im calling the audit log
use one of the with_* methods of discord.Asset
i see if i make other changes like renaming the channel it will fire the after async print
so the issue its probably in that check for permissions
That would make sense
Uhm i have no idea what to do honestly
Okay thanks
wish there were a permissions parameter for channels like for roles lol
But im not too sure what you mean by that
What should i do? do u have any ideas? because i honestly dont
What are you trying to do in your avatar_url_as? resize the image? or with a specific format?
Pfp = message.author.avatar_url_as(size=256)
!d discord.Asset.with_size
with_size(size, /)```
Returns a new asset with the specified size.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
there
robin? π
Actually
I think you can remove that if statement alltogether
Because you're already checking for an action in your audit log lookup
It works btw
Thx alot π
@sick birch Not really. You don't know the rest of the code haha
this is currently just for test purpose to see if it works
it has multiple if statements to check what's going on and what to do
that's the point
also i can run a test without the if statement to see if it would work
@sick birch It works hahaaaaaa
Yes but i need an if statement so uhm.
With this new intents thing basicly every discord.py turorial is outdated
@sick birch i wanna tell u something dumb. I added the if statement back and now it works
π
π€
As if they weren't already
Yeah but like all the 'how to make your own discord bot' tutorials are invalid because you need to set up intentions
I have a question but it's really no 100% bot related. I want to make a leveling system, and I set everything other than the rank part. I did every message sent is between 15-25xp, and saved it in a database, but now I don't know which calculation I should do with that xp to make a rank system. Anyone can help
They were already invalid before, most of them were riddled with bugs, bad practices, and many of them straight up didn't even start
If there is another suitable channel, could anyone direct me to it?
This is the right channel, but I'm not sure what you're asking by "I don't know which calculation I should do with that xp to make a rank system."
Robin how could i check if any role is being added here?
I think the overwrites should have a guild.default_role thing in there
Ok so I want a system that's basically does:
rank 1: 0 - 250 xp
rank 2: 250- 600 xp
rank 3: 600 - 1200 xp
rank 4: 1200 - 2400xp
rank 5: 2400 - 3800 or something.
Just some way to help me get a certain rank from a certain amount of xp
The one i saw never talked about commands.ext, so my path of how i make my bots has been greatly influenced by it. I could take the time to learn about it and how to use it but seeing the word ctx makes me tremble :/
I might be wrong. I haven't worked with the permission system in a while so I may be the wrong person to ask for this stuff
Now, I was never good at math, but I'm not seeing a pattern here. Are we going for an exponential model, quadratic, what's the deal?
everytime you give xp, check the rank the xp falls in and give the user that rank
Robin i will try haha, nothing to lose
yes but in the edit. what's the parameter for it lol
Yeah I am trying to look for some pattern options really
What have you in mind?
Honestly nothing
How do I limit an app command to specific channel, role or permission?
@sick birch if a channel invite gets deleted, can the bot create one with the same url?
or it can create one but with a different url
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
What do you mean "same URL"? The jump URL?
This will only work for text commands
Does this work with slash commands (app_commands)?
like you know a guild invite is being created on a channel.
What's the slash command equivalent then?
Oh, no, I don't think so
it gets showed in the audit logs even when deleted also when created
Yes but pretty sure that the bot can create one back? true?
Is there a way to limit a slash command to specific channel? say I have /hello, can I limit that to just general chat? or will it be available regardless?
Yes, diff URL most likely
Yes, just create a custom check
awesome
What's the param for it? i don't see it in channel
also i think ur right about guild.default_role found something
Alright. I'll go scurry along and see if I can do it. π
@sick birch this won't work sadly
well the default role never changes it's just @everyone
yes but what im trying to do is to see if a role is being added/removed
So compare before.guild.roles to after.guild.roles
if the length is different, a role was added/removed
You have a point but instead of checking the len of the list
wouldn't it be easier if i just make to functions
if not before.guild.default_role and after.guild.default_role:
and
if before.guild.default_role and not after.guild.default_role:
lol won't this be a time saver? and work the same
and if its being added then remove it and if its being removed then add it back lol
this will always evaluate to false
guild.default_role is sort of like a constant, doesn't change and is always there
Well it doesn't matter where it happens the default_role is always the same
I don't understand what you're getting at here
I don't either because the audit logs are making it more confusing
added / removed role to the channel perm thing
let me look up for the invite url thing. i will stop doing this for a bit
I don't find the parameter for the invite do you know which one is it?
woo \o/
im figuring stuffs out \o/
This way of doing stuff is way better than my way. π
How is it different?
Still technically the same thing as what I was doing.. but looks better.
so the slash command still appears in all channels, i dont think I can get rid of that. π¦ However.
def check_channel():
def predicate(interaction: discord.Interaction):
return interaction.channel.id == 932137392738021427
return app_commands.check(predicate)
@app_commands.command(name="truetest10", description="Testing the thing!")
@check_channel()
async def truetest(self, interaction: discord.Interaction):
await interaction.response.send_message(f"Works here!")
@truetest.error
async def on_test_error(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
await interaction.response.send_message("ERROR ERROR ERROR")
``` is way better than
```python
@app_commands.command(name="truetest10", description="Testing the thing!")
async def truetest(self, interaction: discord.Interaction):
if interaction.channel.id in my_channel_list
await interaction.response.send_message(f"Works here!")
else:
await interaction.response.send_message("ERROR ERROR ERROR")
You can get rid of them appearing in certain channels, but I don't know if you can programatically. You need to go through discord's UI
Yeah it's quite extensive. You can restrict to certain members, channels, roles, etc
nvm after doing some testing it doesnt work
I removed all my checks on my bot and just left the command, and despite syncing, reloading, and doing all sorts of shit, it doesnt work at all
Doesn't work how? Users that shouldn't be able to use the command are able to?
So I tried limiting the command to just 1 channel, didnt touch the users. The command was still able to be used in all the channels
Could you send the code please
same as above except without the checks.
import discord
from discord import app_commands
from discord.ext import commands
import traceback
import json, aiohttp, validators
TEST_GUILD = discord.Object(794837147068792862)
class staffapps(commands.Cog):
def __init__(self, client):
print("[Cog] Notes has been initiated")
self.client = client
@app_commands.command(name="truetest12", description="Testing the thing!")
async def truetest(self, interaction: discord.Interaction):
await interaction.response.send_message(f"Works here!")
async def setup(client):
await client.add_cog(staffapps(client))
``` and In the integrations on discord:
as I said. I removed the checks to see if the discord app could do the same thing
Can you see the /truetest command anywhere but #admin-zone?
it's in all channels.
maybe it's coz im bot owner? try creating a new role and setting it to not work for role
I viewed as a new role and.. It's gone!
so perhaps it had something to do with my role?
Requires more investigation, but I'm pretty sure we're onto something!
I'm guessing that, yes. Sort of like how you can restrict certain channels to certain roles, but administrators or server owners can still see them
Well. I'll still put all my checks in places just in case something fails
in discord py 2 how can i make a clickable link in an embed
liek the text will be something like More Iformation Here and then it iwll ead to a link with more information'
in the footer i mean
is there a way to check if the message author has a certain role?
[text](link)
role in message.author.roles
i meant in the footer but it is ok i did it another way
cool thanks
!d discord.Embed.add_footer
!d discord.Embed.set_footer
set_footer(*, text=None, icon_url=None)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Don't think you can have it in the footer but give it a shot
;D
I finally finished v1 of my bot \o/
Still not as ideal as I had hoped. But one day I'll figure out how to do dynamic questions where the user can specify unlimited questions
how do
i add more text thing
so like if i say hey the bot will say hello so how do i add more
more key words to get the bot to say hello back to you?
this was a question. i dont understand your question
okay
@sick birch i hope you dont mind the ping but are you here?
yeah what's up
@worthy mortar
hang on, writing code for you
alr
Could we.. instead provide psuedo-code or an example, instead of writing it for them?
why
i have more context for earlier
well i thought of a better phrasing
how would i go around running 2 bots at once on my pc knowing python only lets me run one at a time
at the moment i have 2 files using subprocess.call on 2 other bot files
have em on 2 seperate files, file1.py and file2.py for our case:
python3 file1.py
python3 file2.py
A better alternative is to dockerize each and use docker-compose up to run both at once
ill try that out, thank you
see if this does what you want:
import random
ArrayOfWordsForBotToAnswer = ['hey','hi','bye!']
LenOfArray = len(ArrayOfWordsForBotToAnswer)
randomNum = random.randint(0, LenOfArray-1)
print(array[randomNum])
actually @sick birch while you're here,
do you have any tricks for making this text more pretty?
i wanna add more things to say to my bot
listname.append?
no
Pretty how? Your options for prettying text up in discord are limited
i mean like i want to make it were if i say hello it will say hello back and i want to make it if i say welcome it will say welcome back
in 1 bot
and i got the hello one donbe
done but i dont know how to make 2
i know limited to discord, but pretty as in, more appealing to the eyes? π
i've pulled most of the data for my bot. just wondering if you have any cool tricks up your sleeve to pretty up the text
@bot.listen()
async def on_message(message: discord.Message) -> None:
mapping = {
"hello": "Hello to you too!",
"Welcome": "Welcome to you too!",
"How are you?": "I'm doing great, thanks for asking!",
"What's your favourite colour?": "Mine is green, what's yours?",
}
if response := mapping.get(message.content):
await message.channel.send(response)
This is a pretty complete example, but it's better than an if/else chain
I think embeds could definitely add a little "razzle dazzle" to it, if that's your cup of tea
so ill add webhooks?
to give it the color
You can use embeds in regular bot messages
oh, really?
!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...
okay ill look into that. thanks robin
Construct one and send it off to your ctx.send()
@sick birch 
No prob. Feel free to ask with any follow up questions you may have
dint work
It only works if you type in one of those keys exactly, word for word. Capitalization matters
It's only an example so I've left a lot of QoL features and improvements up to you. But the basis is there
ok off topic. why python > js for you?
no when i ran it it dint work
Python === JS for me
It just depends on what I'm doing. I'll even mix the two up
i ran it and it dint work @sick birch
Good example, a while back I was making a discord bot, discord.py no problem. I also wanted to make a dashboard for my bot, so my users could change things about the bot from the website. I used Next.js, Typescript, TailwindCSS, PostgreSQL, Prisma, and Next-Auth-JS as my tech stack for it
Well no. You need to send a message in discord that's in the dictionary key
well i used py alottttt and the last 3 months ive been heavily into js
and i have to say i actually really enjoy js
i just make silly mistakes still like append vs push
oh thats actually really cool
sus
I'm with you, it takes a little bit for your brain to be able to alternate between the two. It's like when I'm speaking my native language with my parents over the phone, and quickly switch to English when I have to talk to a friend IRL, if you get what I'm saying
100% lol
I usually stay out of calls, sorry. It's easier here, due to the multitude of multimedia code sharing options :)
What I'm saying is, copy pasting the code I gave you won't work
okay, im going to try this now, thanks
Well you should probably get those red errors fixed
see those red lines?
yes
Hover over them, it'll tell you what's wrong
How can I create Russian roulette, gimme a rode map
Oh actually looks like I made a mistake
it saying
That's embarrassing. That's on me, my fault π³
discord.py for years and I still make mistakes like these.. how dumb
@sick birch π³
i just started
I.. honestly have no idea where to start, if I'm to be honest with you. Games have never been my strong suite
Ohh π no problem thanks
yea well
have you ever rate limited yourself from discord api?
No, are you?
cuz ive done that 3 times, in the last 2 days π
Replit?
Ooo cool , now pls help me too to build one π³
sadly
before i move the bot over to aws i wanted to test it in replit tbh
That explains it. I also use AWS to host my bots, feel free to ping me any time with any questions you may have on that
that message was so long ago, how did you even find it
honestly never hosted a bot on aws
im assuming you use AWS Lambda ?
EC2, not sure why you'd use Lambda for a discord bot though
Discord search option, can u help ? With blackjack command ?
Rode map or any sample code
So I can get an idea ?
π
maybe theres a difference between hosting nodeJS scripts and python scripts? for nodeJS, you can have AWS Lambda which triggers the bots every 10 minutes (very cheap)
Where have you imported discord and discord.ext and defined bot?
Maybe, but serverless computing isn't meant for this. It's sort of like hosting your bot on replit
this explains a lot 
- Dockerize your app
- setup CI/CD
- automate the whole process
I mean for chat . Like muting with time
like i said i really should look into aws more. it explains why the bot would always get stuck thoπ
thanks robin
when i fully program the bot (in 1-2 weeks) you can expect to hear more from meπ
Can't wait π
Guys how we can mute a user with time in dpy?
if u mean temp mute then u need asyncio.sleep
tempmute adds a mute role timeout is a discord feature which is utilised before it was not there thus tempmute was made now that its there its better to use timeout
So how can I timeout a user with time?
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to use this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
anyone know what package to install to read chrome push notifications Itβs not toast as that is used to create notifications, I want to read the pop up message that I get sent from chrome and then send the ctx to a discord channel
Like i have it time like this 2hr 5mins so how can I convert it to timedelta?
@robust fulcrum any idea about blackjack or roulette ?
How?
Whats blackjack?
why donβt you just look up on youtube / google: βdiscord python gambling gamesβ
and build from there
or just look up discord gambling bots, copy one of that
can someone help with this error
import discord
from discord.ext import commands
class ping(commands.Cog):
def __init__(self, bot):
self.bot=bot
@commands.Cog.Listener()
async def on_ready(self):
print("Bot is online")
@commands.command()
async def ping(self, ctx):
await ctx.send("Pong!")
async def setup(bot):
await bot.add_cog(ping)(bot)```
its listener
import os
import discord
from discord.ext import commands
intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix=",", intnets=intents, help_command=None)
async def load():
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
async def main():
await load()
await bot.start("")
asyncio.run(main())```
for outdated tutorials?
What are you looking for?
Quite frankly im not looking for anything
Do you need help with something?
bruh
Have i asked a question?
You just said you looking for anything
Where exactly?
Oh I read it wrong, sorry
i didnβt realize 6months ago was outdated
Well it is
sorry
next time iβll just build the bot from scratch and instantly open source it
π
Atleast you didnt waste your time looking at Lucas videos
@silk fulcrum Could you help with this?
youre on 1.7.3 lol
last line, what the heck is await bot.add_cog(ping)(bot)
bot.load_extension returns None uppon calling it lol
i should be a bit more careful with my wording
or what?
you will hurt better discord users? lmao
ok
ok
I was watching a YouTube video for cogs that's what they did I'm gonna be honest with you
dude, stop. the message you sent is sent at 11:42, and itβs 11:43, itβs outdated.
who asked?
I am? I thought I upgraded
I do pip install git+http=s://github.com/Rapptz/discord.py right?
Ok I downloaded that hopefully it works now π
http=s:// wtf
I did that so it wouldn't send link
it wont in an inline block
- classes should be named with capital letter + name of function
pingwill be shadowing the class name, so rename the cog toPing await bot.add_cog(Ping)(bot)is just not a thing, how do you think this works? I don't think even stupid tutorials would've provided such awful code, I think it's you typo, because bot should be provided inside the cog init so...add_cog(Ping(bot))
If you put it into back quotes it won't attach any embeds yeah
So what should I do with last line?
... inside the cog init so ...add_cog(Ping(bot))
am i stupid or people sometimes dont read?
No you're not I just don't understand
what exactly you didn't get?
you didn't get that ... here means await bot.?
No I didn't know if you wanted me to replace or what not
await bot.add_cog(Ping)(bot)
i don't think even stupid tutorials would've provided such awful code, I think it's you typo
how is returning a callable awful code? i think you mean, no tutorial would suggest that return type?
......
What is this guy talking about
im paranoid sorry
do you think if there is code that is garbage not good weird return type and there is new code that looks similar you should replace it or not?
replace
I'm still getting this in terminal
then what is the problem?
I already replace it
^
if you mean you replaced it with this then you did nothing except changed ping to Capital letter
Isn't that what you said tho?
Oh the ) next to Ping
I did not see that
Nope
still same error?
How do I check because I download it
press a run button?
Alright
its python or py on windows
doesn't it upgrade at least to python3?
either way, you should be checking libraries that can be causing name clashing so you should be checking evey lib installed with pip list
So do I do python -m pip show discord.py?
python -m pip list
@slate swift
github release π
yeah, my bad, my command was incorrect
?
You should delete nextcord, discord and discord.py
well... idk for what do you need nextcord, but alright it doesn't overlap
How do I delete
pip uninstall package
I guess they just murged with my other project that I deleted or something like that Idk
should invoke pip as a module ofc
pip nextcord | discord | discord.py pip uninstall -y @slate swift
woops
forgot
pip freeze | nextcord | discord | discord.py pip uninstall -y
no wait that is trash
bruh
just remove them manually
pip uninstall -y nextcord
pip uninstall -y discord
pip uninstall -y discord.py
and then pip install -y discord.py
ok
pip install discord.py
Probably
what should i do
Change password immediately and you will be fine
Did you click the link fully?
if they got token it wont help
and 2FA too
it didn't bring me to the sight but I saw a flash of a little window pop up on my screen
Token gets reset on password change fyi
it closed right in like a sec
Change pass
If u didnβt enter/scan anything then u may be fine
actually?
Yea
For sure
Is that correct?
yes
im pretty sure most links redirect you to a look alike and make you sign in to "claim" your free month of nitro
Some do fake verification
Okay I'm gonna try the code now
try
And then they do something like headers interception or smth
πΆββοΈ okay gonna play minecraft, bye guys
...
you mean a MITM attack? i doubt it, most use look alike domains
I clicked the link to try and find if it was a scam or not. I didn't enter any personal information but im thinking it might've hacked/automatically logged in using my saved passwords
fr..?
Your cookies?
not sure on that but where did it redirect you? send a ss of the page
and btw nitro gifts dont use buttons that redirect you to any where lol
anyone know why you can't input a user id in the args of msg.guild.ban() command, it says that it needs some sort of clas
it opened a window but whatever i should be fine
discord.gift/0137132810123 like that
im pretty sure it needs a Member object
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=1)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have the [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") permission to do this.
wait nvm, can you show your error?
in d.py can i disable reply mentions by default, but be able to specify mention_author=True in replies when i need to?
what are you trying to do exactly?
I want to ban a user with their user id
await ctx.guild.ban(discord.Object(id = member.id)) You can try that sorry if its incorrect
When doing a slash command, how can I set the paramaters to have a placeholder or whatever it's called? in here I want it to be like 'name - type your name'
Sorta like how it says 'Introduce yourself'
Is that possible? Personally have never seen it
idk if it is lol
Description?
No. Description is for the command itself
Iβm pretty sure options can also have descriptions
They can
how?
I think at least
Thatβs an entirely different ballpark my friend
I'll use the main description for now. and yeet out an error if it's wrong
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
Iβm not gonna lie, the documentation for anything slightly involved using app commands is sorely lacking in documentation
We have a few basic examples, and the documentation only really describes methods and attributes, not how to use them
When I was making my example contributions to discord.py, I had an incredibly difficult time since I was one of the first people to use the new feature (it was the night dpy came back)
Lacking documentation is one thing, but not being able to find resources online, or being able to ask anyone else.. god was that a headache
I think my real issue is whenever I try and ask a question, despite completely explaining it in detail, I often encounter trolls.
Here or on the official discord.py server?
here, and I wouldnt say trolls but more or less people responding with stuff I've already explained doesnt work
π§ thatβs most likely a communication issue, not your fault though! Communication is so much harder online than it is anywhere else
Probably.
Being able to convey your question in such a way that itβs crystal clear, and for readers to be able to read everything and not skipping.. requires conscious effort
and that's fine. It's whatever. Frustrating when you have to go around in loops repeating yourself
Yup and unfortunate thereβs no βone size fits allβ type solution here
Yeah that works thanks
π
are there any cases where hybrid_command fails to replace the command deco for prefix command in my code i had prefix commands before and i replace command with hybrid_command and few commands stopped working most of them are working tho
whelp. outside of copying and pasting my Modal classes, I can't seem to figure out how to make them dynamic
You can use modal.add_item with an instance of TextInput cause Modal is a subclass of View
Has anyone successfully sent push notifications from Chrome to a discord channel? This is not toast right?
not sure if that is toast or not but anyways Chrome has API
Based on a quick google, i believe it uses webhooks
Or you may use a discordbot if there's an API as @silk fulcrum said.
welp, now I look like an idiot π€¦ββοΈ
thanks
!pypi pychrome
I've never used push notifications and still yet to find a use for them so I don't know about it
not sure if this is the right library... id probably make my own requests
Just a website I trade on, it has push notifications for Android only, no iPhone. So a work around I was thinking to send the dektop notifications to my discord
Maybe google websitename api for example reddit api
or websitename developer
there may be an api you can connect to
ahh i see
It's usually the first thing I do
yeah if you want to get something from a site that has an API there is no need to go for chrome api
Then from the API, you can create a basic bot that sends whatever data you want
I recommend using AIOHTTP btw.
It does not have API, only allows you to connect to a private IRC protocol
are you sure? what's the site?
or its some robux miner so you can't send?
holy crap this looks like an old af website..
yeah
<=2007
I didnt even know websites could still look like this
I been there since 2005
go to russia
π
yeah it doesnt seem to provide an api
but
but but that will be hard to get this text
you are not logged in
oh nvm, you need an account
well, in your case there are 2 options:
try using chrome API
delete this website from your history
i guess
@slate swan out of curiosity.. do the urls look like this: https://djsp.org/trading.php?item=a&item=b?
coz you might be able to just do a simple query on the specific items and extract the data
iirc he wants push notifs
Sure sure.
but push notifs are probably just an update on whatever has changed right?
So, if you can query a URL instead and get the same data, does it matter?
me too
So his options are to either to some form of web scraping, figure out the chrome api thing, or try and do a URL query
well, some people have made scripts for a game to automate a trade to a user buying items within the site. They have somehow made a script to use the notification of received gold/description. The script then uses what the buyer put in the description to automate a trade within a game
surely they are doing this though IRC protocol? idk.....
Β―_(γ)_/Β―
can anyone link a discord bot template from the discord.py docs, i cant seem to find one.
not sure what template means here... but probably this? https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#special-converters
no i dont think so...
he prolly meant some broiler plate
like some example code
lmfao "broiler plate", but yes
one where the bot is a class with methods
i don't think there are examples with 2.0 out yet
not dpy docs but: https://gist.github.com/Ash-02014/426ec7974f705303a2363c739dd82309
yeah i made a bot a while ago that has commands as regular funcs
i think he wanted one with subclassed commands.Bot
but in order to use the new commands you need to await bot.tree.sync()
example
yeah I guess I will try chrome api first if not, maybe URL query
yeah either use setup hook or a command to sync
interesting, couldnt find anything about setup_hook for some reason
u can use jsk sync also
but i got it now
jishaku has a sync command
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
yeah docs has that
so is it better to use the class-based approach?
nothing better or bad it's more pythonic and more versatile
because you only need to sync when something related to slash command changed
setup hook is called only once so technically for dynamic commands are better
__A__uto __S__yncing (your command tree) __S__ucks, and here's why:
Syncing your command tree automatically causes extra unnecessary requests to be made, this is because you only need to sync when commands are updated.
*see ?tag whensync for a more enunciated list on when to sync.
What syncing does is send your commands to discord for one guild or globally. If you haven't changed your command's descriptions, added/removed commands, changed names, parameters, etc. you shouldn't sync, since you'd only be updating discord with the commands they already have without doing any changes, which is pointless and a waste of an API request to a limit with an already tight rate limit.
*see ?tag whatsync for a more enunciated on what syncing is, and how to do so.
Where should I sync instead?
It's better to sync using a normal (message) command (or even an on_message if you prefer Client) You can even use just a simple eval to do so.
*for example:?tag umbras sync command
*But I don't have the new message content intent... What now?
Bots can still receive message content when the bot is mentioned in it, or in DMs! You could set the bot prefix to commands.when_mentioned
*Why do I get a Missing Access error when trying to sync to a guild? -> See ?tag mas
i just use the jishaku sync command tbh
ah this is helpful
what is jishaku?
Jishaku -- jsk
A debugging and utility extension for discord.py bots This provides an eval command and much more!
Source: https://github.com/Gorialis/jishaku
Docs: https://jishaku.readthedocs.io/en/latest/
Requirements:
- Python 3.8
- git (https://git-scm.com) (for the dev version)
Installation:
- Download jishaku on the command line using pip:```py
pip install -U jishaku
or the dev version:
pip install -U git+https://github.com/Gorialis/jishaku@master
2. Load the extension in your bot code before it runs:py
await bot.load_extension('jishaku')
If you would fetch the current commands and see which ones need to be synced that wouldn't be a bad idea
ok
Idk if dpy does that internally but would be better if it did
another question, for testing slash commands, its faster to sync to a specific guild, but that creates an issue with duplicate commands, since both global and guild-specific show up in the slash menu then
i did this and had no problems with double commands
self.tree.copy_global_to(guild=discord.Object(id=12345678900987654))
await self.tree.sync()``` this is from gist
oh so this would only sync to a specific guild?
yes
alright
so I coded a discord bot in repl.it and my main problem is that whenever the word comes in a sentence my bot replies to it. like if i wrote a command to reply good morning to a text with "gm" it will reply good morning when a person sends a text which just contains gm but i want my bot to reply only when somebody says "gm" and not his sentence contains the word "gm"
like if somebody says "my weight is 50 kilograms" it replies good morning just cause the text has "g" and "m"
can you show the code where you check the message content?
one sec
if message.content == "gm":
actually they are like this. like there many words and many replies so it happens in this command
^
try if any(word == message.content for word in greeting_words)
basically what watchYourCache said
Why did you just leave earlier I still need help Bru
i was playing minecraft
what's the problem?
Still the same error from earlier I gave up when u said ur gonna play minecraft
do py print(discord.__version__) at the start of file
aaah thankyou so much it worked thankyouu π
little python
output: discord 1.0.1.final
πΏ
when i got push notif i actually thought he sent that
π¦
Master128 > Master86
Damn nice
duck-pond
U r still living in 2019 or smth maybe before that
2005
I'm the 2019
Nice
his living at 0x7e66f0b1f0
The latest is 2.0 and u r still using 1.0 nice!
2.1*
lmao
i need SERIOUS help organizing my code
Thought there was only the original 2.0 release till now
nothing changed but danny updated the version on github
I need SERIOUS help to make me code again
!pypi discord.py
so if you download dpy from github it will be 2.1
this bot is almost up to 5k lines of code and one of the files is 3725
Ah, ofc on GitHub its gonna be a greater version
just start on it
OOP
No motivation and idea ;-;
nah his code is "oops"
oops
that's very helpful 
yes
i somehow managed to rewrite my bot
well im still doin that
memory addresses locked since 2019
send the link of the repo
My GitHub is on my profile
I don't think I should share the link here
The link is in my About Me tho
k
hi
is it the discord ai chat bot?
i have moved on from yesterday where i didnt get the bot working
but i have a new error
send it
the bot does read my text
2022-08-20 06:28:40 INFO discord.client logging in using static token
2022-08-20 06:28:41 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 36c2593bdf71bc9668c9f6912c9426e3).
We have logged in as CCS#4524
MISTY: (general)
it comes blank in console
intents = discord.Intents.default()
intents.typing = True
intents.messages = True
client = discord.Client(intents=intents)
is the problem in intents?
these are the ones i used
@vale wing
channel = discord.utils.get(bot.get_all_channels(), id=channel_id)``` is this the correct way to get the channel ID where cmd sent in?
i sent
@fresh hedge
in discord.py to be able to use message content intent you need to set
intents.message_content = True
what will the command actually be
to add that channel to allowed channels list
i tried this earlier, this is what i get
raceback (most recent call last):
File "main.py", line 37, in <module>
client.run(TOKEN)
File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 746, in start
await self.connect(reconnect=reconnect)
File "/home/runner/disc-bot/venv/lib/python3.8/site-packages/discord/client.py", line 672, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.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.
you could just typehint channel and call .id on it
you need to go on discord developer portal and enable all the 3 privileged intent options
Yea
ok
maybe I can collaborate (not for the ai part) π³
how to do that?
Haha, the AI part is all done. What I have to rewrite is the client side (the discord bot)
@glad cradle dude!!!! thanks a lot. had been jamming my head on this for the past 15 hrs
omg
you're welcome
@some_bot.command()
async def cmd(ctx: commands.Context, channel: discord.TextChannel) -> None:
await ctx.send(f"the id is {channel.id}")
# do something
I forgot if ctx is commands.Context or command.Context someone lmk
it said its for bots for more than 100 thats why i didnt really think its necessary. however i did think abt trying it earlier but didnt
if your Bot will become larger you will have to pay more attention to these privileged intents, very often the bots that have them all active are not approved to become verified
commands.Context
thought so
then maybe I'll create some pull request π³
Nice
doesn't output that message
What's the issue
.
have you replaced @some_bot?
yes
send your code
how does it the command look now
@bot.command()
@commands.is_owner()
async def channel(ctx: commands.Context, channel: discord.TextChannel) -> None:
await ctx.send(f"the id is {channel.id}")```
how are you invoking the command
!channel
you need to mention a channel as well
that could be a stupid question but are you the owner of the bot?
my bad I got it
what did you do
!channel #general
read the code we send, so you understand it instead of just copying and pasting
π¦
Ok mr.python
I don't know a lot. I just want to learn π
ok mr.python_learner
π€·ββοΈ
the discord.py docs give this example for a check decorator
def is_in_guild(guild_id):
async def predicate(ctx):
return ctx.guild and ctx.guild.id == guild_id
return commands.check(predicate)
my question is, can i somehow put this inside a class?
not sure how to work around the self and @staticmethod stuff
yeah he is, sadly offline though
@slate swan π₯Ί
Why do you not want it to be a static method yet put it inside the class
Well if u want it to be a check then you canβt access self. Static methods are a method but without the self parameter. If u want self then put it directly inside the command
yeah, im probably gonna have to get rid of staticmethod
so i need the decorator to access self
Why do you
because a bunch of commands should only run if some self.var is true
Is it in a cog?
yes
You can do a cog check
is that different from regular check?
!d discord.ext.commands.Cog.cog_check
cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter, `ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
Returns False or True whether to block or allow access to the command
i only want to decorate some
Ok so you need a check that depends on self?
yes
back when i wrote this code i used a regular non-check decorator
@staticmethod
def game_command(func):
@functools.wraps(func)
async def decorator(self, ctx: Context, *args, **kwargs):
if self.game_started:
await func(self, ctx, *args, **kwargs)
else:
await ctx.reply("No game started.", mention_author=False)
return decorator
and it works
before invoke exists, but I don't think it can work for some amount of specific commands
is self.var required to be in that cog?
Is it some sort of a cooldown
so while its false, a bunch of the commands need to be disabled
but if you run start_game, then the others are enabled
and obviously i dont want to copy-paste this check into every command, that was the whole point of decorators
any ideas how i can convert this general decorator into discord.py's check decorator?
you can probably use cog_before_invoke
oh wait... i dont think you can prevent command executiion in before_invoke π
i thought about smth like thispy async def cog_before_invoke(self, ctx): if ctx.command.name not in your_commands_those_depend: return if not self.var: return


would you rather print("\x9b2J")?
i'd rather not do that at all
doesnt even work on half the terminals out there
more code, I can't see a problem in code you sent
anyone know what the giant ass error is? I didn't change my code and I'm suddenly getting this
ratelimited
429 too many requests
(replit is trash)
just run in the shell kill 1 @mossy warren
I see that, what type of requests specifically
replit's
what would you suggest for running code 24/7?
oh so it isn't a discord thing
replit has shared IPs for users, as many users use replit for Discord very often Discord ratelimits these IPs
check the thread in this channel
nice it works now, thanks a lot
@mild lava Does something like this work
@staticmethod
def in_game():
async def predicate(self, ctx: commands.Context) -> bool:
if self.game_started:
return True
await ctx.reply("No game started.", mention_author=False)
return False
return commands.check(predicate)
@commands.command()
@in_game()
async def some_game_command(self, ctx: commands.Context) -> None:
...
tried, but d.py passes ctx into the self param, and then ctx is missing
cool thanks, I already see some good options
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:
with open('allowed_channels.txt', "a") as f:
contents = f.read()
if channel.id in contents:
await ctx.reply("Already there!")
else:
await ctx.reply("Successfully added!")
f.write(f"\n{channel.id}")
f.write("\n")``` Why doesn't this code work?
error?
can i make methods into bot commands under the bot class, or do i have to use a cog?
you should use your f.write's inside the with
you exit with ... as f and then use f
method into bot commands? π³
you mean like
async def command(smth):
def method():
smth
smth```?
what's that shit
use aiofiles
i mean like
class MyBot(commands.Bot):
def __init__(self): ...
def on_ready(self): ...
@decorator?
def some_command(ctx): ...
that too....
is Master86 dead?
why u need him?
does Master64 exist?
and no hes not
yes
Cool
nah, you cannot make commands like that
so i need to make a cog
so this? ```py
@bot.command()
@commands.is_owner()
async def addchannel(ctx: commands.Context, channel: discord.TextChannel) -> None:
with open('allowed_channels.txt', "a") as f:
contents = f.read()
if channel.id not in contents:
await ctx.reply("Successfully added!")
f.write(f"\n{channel.id}")
f.write("\n")
else:
await ctx.reply("Already there!")```
I think that you could do this, btw self is missing in some_command function
nah that shouldn't work
@self doesnt work
he can't?
because self is not available in the scope where the decos are
π
can he?
maybe commands.command()?
use aiofiles
like i dont want to go make an entire Core class for a few commands
but it won't write into the bot
whats the command
(and do this for every bot i have)
!pypi aiofiles
well, @bot.command exists
π
you can use self.add_command though
boop beep baap
!d discord.ext.commands.Bot.add_command
add_command(command, /)```
Adds a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") into the internal list of commands.
This is usually not called, instead the [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.command "discord.ext.commands.GroupMixin.command") or [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.group "discord.ext.commands.GroupMixin.group") shortcut decorators are used instead.
Changed in version 1.4: Raise [`CommandRegistrationError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandRegistrationError "discord.ext.commands.CommandRegistrationError") instead of generic [`ClientException`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientException "discord.ClientException")
Changed in version 2.0: `command` parameter is now positional-only.
imagine command1_callback command2_callback