#discord-bots
1 messages Ā· Page 93 of 1
Bruh š¤¦
make another property in your player table
name it like "required_exp_for_next_level"
Ok
and "exp_since_last_level_update"
Can I have one suggestion from you?
what
Should I reset user exp when they level up?
no
idk
Thanks for help tho
Do you know any free hosting service for discord bot?
how old are you?
hmmm 13
do you have like a spare PC or raspi
And can provide an internet connection and power constantly
i'm trying to get a bot to send spotify url on command, but i can't get it to work. i tried to follow a youtube tutorial.
async def track(ctx, user: discord.Member = None):
user = user or ctx.author
for activity in user.activities:
if isinstance(activity, discord.Spotify):
await ctx.send(f"https://open.spotify.com/track/{activity.track_id}")```
it says ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'activities'```
sorry, i'm really new to this... anyone know what i'm doing wrong?
Apparently ctx.author is of type discord.User. discord.User objects don't have activity and activities attributes
Try using user: discord.Member = commands.Author instead of doing the user = user or ctx.author thing
thanks for the tip, @brazen raft but now it said : AttributeError: module 'discord.ext.commands' has no attribute 'Author'
Are you using discord.py?
yes
Latest version?
Which I think is 2.1 now
You can update with
py -m pip install -U discord.py
if you are on Windows
Make sure youāve enabled member intents. It may only give user objects unless you have that enabled.
Thanks, @wicked atlas i didn't have that, but i still get the same message
Also, I'm on the latest version it seems
Youāve enabled them both in the dev portal and in the code?
I'm pretty sure there's smth wrong with the code please let me know what is wrong
The code - https://pastebin.com/Z9CNGzG3
I would be really grateful if u answered by replying to this is message
Thanking you in anticipation...
Iām not about to play the code version of Whereās Waldo. Whats wrong with it?
It doesn't add values into the columns...
basically the end part of the code is crucial
looks like i hadn't in the portal @wicked atlas do you know if i need to generate a new token, because i still get the same errors... :\ AttributeError: 'User' object has no attribute 'activities'
thatās more of a #databases problem
I tried DM, but it seems to be working in server now.
š
is there a reason it doesn't work in DM?
You wonāt be able to get Member objects in a DM, it will only give User objects, since a Member object represents a member of a server
ye, no
I'm pretty sure it has to do with
discord
you didnāt provide any error 
I'm not getting any error, k just let me copy paste the code, there is smth wrong with the code just let me know what it is
^
I just said what's wrong... just review the code, no need to run the code
async def planets(user, button: discord.ui.Button):
button.labal = await Planet
db = await aiosqlite.connect('player_data.db')
async with db.cursor() as cursor:
await cursor.execute("INSERT INTO planet VALUES(?, ?)", (user.id, button.label,))
await db.commit()
return
``` this code isn't even used in the class????
Also button.labal = await Planet???
What's more efficient? Photos in files or download via link?
and will the bot go faster on hosting than on localhost?
import discord
from discord.ext import commands
- If you want to display a picture link is faster since you don't have to upload it first.
- Depends on the hardware & ethernet speed, generally since hosting's have faster ethernet and your pc doesn't need to stay on it's the best option.
I am asking because after the next interaction the command does not keep up and sometimes it will display the content and sometimes not (I have a localhost)
no problem, everyone started out that way
Well it taking some time to display is because Discord is fetching the image and show it.
Pretty much otherwise you would need to upload the picture everytime.
It is difficult, if it is a more efficient method, I will use it
Well it's unethical, why would you use resources for something as small as a faster loading time for images if people are used to Discord slow and annoying lazy loading anyways lol
but sometimes it is so that the interaction will not take place at all because the waiting time was too long. Unless, if I give it to hosting, it will change
Guys how we can host a discord bot free on Oracle?
iirc you need to be a student
Hmm isn't there any free hosting service other than the terrible replit?
Btw how we can add arguments to slash command?
how i can create a custom function in discord.py?
class Game(commands.Cog):
def __init__(self, bot):
self.bot = bot
bot.add_view(JoinGame())
async def create_dolofonoi_chat():
# do something
@commands.command(alias=["Start", "START"])
async def start(self,ctx):
embed = discord.Embed(title="Start Game.")
await ctx.channel.send(embed=embed)
create_dolofonoi_chat()
wdym by custom function
š
# its cog file
class Game(commands.Cog):
def __init__(self, bot):
self.bot = bot
bot.add_view(JoinGame())
async def create_dolofonoi_chat(self):
# how i can define the guild because im getting error when i try this:
guild = self.bot.get_guild(884589903210479637)
Any free bot hosting? I used heroku but yeah..
What error
thereās not really any free bot hosting that doesnāt have some type of back draw to it
I mean 5 bucks a month isn't the end of the world.
wdym.. is there any like heroku?
wdym, by wdym, he litterally is saying theres no good free hosting without a sort of catch
what do you mean by "catch"?
like what about this
https://bot-hosting.net/
Hey, you want to host your bot for free today and with a good uptime? Then you are exactly right with Daki, convince yourself today!
There's always a catch with free hosting sites as you cant use a companies resources for free, legally, without given them some sort of exchange, most of the time it's money
i wonder if you could create a hosting solution based on ads
Think for a second. Why would someone host your stuff on their expensive hardware for free without there being some sort of catch. Deta for example collects lots of data and reserves the right to use your software for reasons "within their company"
ur joking
the ultimate free hosting solution: use your pc?
Especially if thereās hundreds and hundreds of people trying to participate in "free hosting" they will have to continue to scale their hardware to keep up. And itās not cheap.
a raspberry pi is actually a pretty neat way i've seen people do it
For 24/7 hour hosting
I donāt think so.
Running your computer 24/7 365 days a year isnāt good for its health.
I've been doing that with my pc for about 7 years
With no rest whatsoever?
It's fine if you keep the pc clean tough.
Physically as well.
In theory, in some ways it's better for your pc than turning it off an on
You can dip your whole pc in water and let it dry for a week and it will be all fine.
Raising components to 60c or whatever temp and then letting them cool to room temperature is constantly expanding and contracting material
Thatās what servers do
I understand that
ah yes submersion cooling
idk then.
servers are just pc's with extra steps.
I believed there was difference because one is dedicated for that job with consistent maintenance
Both are computers
Bottom line
You can run both 24/7 and work just fine (given you maintain it)
heck your phone is a computer
It's just different names because people in that industry like to have fancy words.
Yeah, and both do exactly the same thing
I could prob buy a server and use it as my home computer and play games on it or whatever
Similarly companies can buy a dell optiplex and use it as a server
what kinda games you gonna be playing on that?
most servers donāt come with gpus
from what Iāve seen atleast.
Eh a lot do
Itās good processing power
what kinda servers you be gettin?
Any you can play on your own home computer
The majority most likely only has an igpu
Intel graphics
Good enough for me :))
If you wanna run your own server just buy a raspberry pi though, uses no energy and keep it on 24/7 and forget about it
Ryzen graphics
intergrated lmao
well yeah.
More than enough for bots
Iām just saying Intel graphics because thatās an example of integrated graphics
I donāt know where mine is but it responds to pings š

How much power does one actually use, how long could you run it on a lithium battery
Youād have to check the specs for the power supply
Just slap in a EPYC 7742 and ur good
5 watts at full for 4
Gonna be rough finding a server that has a gpu that can run the newer games
I mean most quadro's are pretty high end.
Model zero can run on a 21700(about twice the size of a AA battery) for 28 hours
Does someone know how I can ask the bot in which channel a specific user is and he replies with the channel. As example I do:
!channel {username}
and the bot replies with the channel where the user is in so I can click on the channelname and I can join etc, example:
The user is currently in the voicechannel {voicechannel}
!d discord.Member.voice
property voice```
Returns the memberās current voice state.
The voice channel that the user is currently connected to. None if the user is not currently in a voice channel.
thanks mate, I will read through it
Anyone able to help in help-broccoli regarding discord bots??
i hav to go soon so it will be very helpful
guys
how do i make it so when i click a button the bot its message will be gone ? it works in dm but not in server
which message?
the bot its message
but which message?
the bot sends many of 'em
and you input numerous things
do you wanna delete the message the button is contained in?
Is it possible to send a discord bot message without having it to react to a message
await interaction.response.edit_message(embed=embed, content="Quitting!")
async for message in bot.get_user(ctx.author.id).history(limit=1):
if message.author.id == bot.user.id:
await message.delete()
await asyncio.sleep(0.5)```
or to basically any kind of event
just pass the message when you create the view?
@somecommand
async def command(ctx: commands.Context):
view = MyView()
view.message = await ctx.send(..., view=view)
''' then inside the button callback'''
async def button_callback(...):
await self.message.delete()
ok
yeah sure, you could set up a task
nope doesnt work
NameError: name 'self' is not defined
what...
?
well idk how thats why i asked
got a handy link to the docs, discord.py docs are all over the place, can be quite annoying. Excuse my lazyness
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
inside the command or inside a View subclass
you should create a subclass tbh, 'cause I don't see how you'll make no subclassing work in this case
? i dont even know what a subclass is
so i showed my code is there a way to make it the same only for servers ?
instead of dms
there is a way, but is quite messy
and could be inaccurate
ok what is it ?
and may end up deleting a wrong message in very rare cases
you could fetch the history of the channel (last 5 messages) with a check that checks if the message was sent by the bot and the content of the message matches...then you could delete it
thats the code i send
here
you know what nvm do you know how i disable buttons ?
just for a fact, you are fetching the invoker's messages and comparing their id to your bot's id like it's ever gonna be same.
for child in view.children:
child.disabled = True
#edit the message with the new view
lmao
and you know how i put a cooldown on a button ?
you'll have to implement that by yourself
why ?
...
?
it isn't implemented by dpy itself, so you'll have to write your own logic for that
so how do i use the disable button thing ? it isnt working
code?
like where do i put it ?
?
wherevee you wanna disable them from?
from the other button
em = discord.Embed(description=f"ā
Successfully sold!", color=color)
await interaction.response.edit_message(embed=em)
await update_bank(ctx.author, mul)
for child in view.children:
child.disabled = True````like this ???
you have to edit the message too
what message ?
?
Can someone help me to make a command with discord.Member.voice and discord.VoiceState.channel? I dont know how to use them to get a good output: Im new in discord.py and cant find videos/tutorials how to use it
What exactly do you need help with? Got any code or errors?
I dont have code yet because I dont know how to implement it. Could you maybe explain me how to use and implement it?
I just need a simple command where I can search the channel where a specific user is in. Because on the server there are temp voice channels so its hard to find a user in a channel. So I want a command where I can write:
!location {username}
and then the bot replies with the specific channel so I can click on the channel name to get to the channel. And if the user is in no channel it just responds with:
the user isnt in a channel.
But I dont know how to implement it bcs im new in discord.py
Iām not sure what youāre trying to make
Nvm, you just sent it
Forgot to send it before, sorry haha
How do you send messages without user sending one first?
If you dont understand, I can make a quick video as example
!d discord.Member.voice
property voice```
Returns the memberās current voice state.
Itās that easy
Someone already sent that earlier but I dont know how to use it yk
Im kinda lost but I cant find a tutorial or smt to it
You just call the .voice property on a member object
Thats the thing, how do I do it. Could you explain that to me
Im completely new to discord.py
I new to make a new bot.command, then async def location as example and then call discord.Member.voice but how do I do it that I can ping the member and it replies with the channel name then
it returns the voice state, basically what are they doing in VC
Can I maybe call you in DMs or we go in a voice channel and you explain it to me? Only if you have time right now
sorry I do not have a mic atm
and it's simple, you get to know about voice state using that
Can I stream for you and you tell me what to do and maybe explain?
How can I convert things such as 5m or 2d into a datetime object so then I can use it for member.edit(timed_out_until = ā¦)?
it's very simple, let's take an example some ppl are in vc with VoiceState you can check whether they are muted or not, streaming or not and various things
string slicing
could i get an example please?
Can you check your DMs real quick?
# assuming your timeout duration be a variable named duration
units = {'s': 1, 'm': 60}
timeout_time = float(duration[0:len(duration)-1]) * units[duration[-1]]```
So how could I host a discord bot on my raspberry pi and be able to easily modify it with SSH?
Tired of replit constantly getting banned
when a bot sends a message too big, does it become a file?
It gives you an error that you exceeded the character limit, you could put the text to a file and send that instead

Yep
If it's possible, how would I do it?
install python3, setup the folder, create a bot & create systemctl instance
Make sure you install the correct python3 version
What's systemctl?
You're going to use it for running the bot on background
Would it run alongside omv?
omv?
I think the Pi 3 may be better. I'd have better access to it anyways
Also, what would be the chance that I get IP banned?
Not sure, why do you think you'd get banned?
I'm setting up a cooldown but it's in case some moron in the server decides to spam commands
You'll get rate limited first
You sure they are going to request your bot 50 times per second? xd
That's the treshhold?
So should I make the cooldown so you can only use a command once per second?
Perhaps, your choice. But I think there's no need for a cooldown (but that can change when your bot is going to be used in a lot of servers)
Either way, if some moron starts spamming stuff, I'd take the bot offline
okay xd
I read somewhere that you can use git to edit the discord bot with ssh
I use Vscode with remote ssh extension
Would 1GB be enough for the bot or should I run it on my Pi 4 (4GB) that's running a NAS server
1 gb of ram or storage?
RAM
Atleast 2 GB's is recommended
So 1GB wouldn't work?
You can try it
Welp then your good
where should i go to learn about mongodb
Codeacademy?
ok
integer
@commands.slash_command()
async def timeout(self, ctx, member: disnake.Member):
await member.edit(timeout = "60")```
number without " "
I can help you with that!
I have a code for it, just accept friend request.
I already fixed it but thanks anyways
which library is this?
because discord.py takes datetime / timedelta for a timeout
not an int
and also it's until and it's an arg, not a kwarg iirc
oh wait you are using edit
i dont think edit has timeout at all
This is disnake
Perhaps different?
Yeah it takes the kwarg and also a float
But not a string
can someone help me create something with python dm me if your willing to it inculdes a link so i canāt send it here
Disnake has edit timeout and accepts float and datetime, discord.py has timed_out_until and only accepts datetime
disnake.Member š¤
And dont hit me with the:
import discord as disnake
```
yo, anyone here know how to save a file a user sends? Like if I attach a file with this message, I want the bot to save that file as a varaible. Thx
Hey!
I am trying to make an afk command
Code:
https://hastebin.com/orocebozow.py
I want it so, if someone is afk, and someone pings them it responsds with this user is afk
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I guess you could store the afk users in a list and then in on_message check if they have been pinged
how would i do that?
Sorry, I haven't done this in a while so I don't remember much
intents = discord.Intents.all()
bot = discord.BotIntegration(intents=intents)

No documentation found for the requested symbol.
How do I get a users id from an on_member_join event?
member is just their username and descrimator. Ive tried member.id (how I remember it being from awhile ago, no luck)
I forgot to format the string....
gotcha
How would I save a file a user sends in discord. If I enter a file rn I want the bot to save that attachment as a variable.
!d discord.on_thread_remove
discord.on_thread_remove(thread)```
Called whenever a thread is removed. This is different from a thread being deleted.
Note that you can get the guild from [`Thread.guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.guild "discord.Thread.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
Warning
Due to technical limitations, this event might not be called as soon as one expects. Since the library tracks thread membership locally, the API only sends updated thread membership status upon being synced by joining a thread.
New in version 2.0.
what is the different between thread removal and thread deletion?
C:\Users\kaelm\AppData\Local\Programs\Python\Python310\python.exe C:\Users\kaelm\PycharmProjects\mainbot\bot.py
Traceback (most recent call last):
File "C:\Users\kaelm\PycharmProjects\mainbot\bot.py", line 2, in <module>
import discord
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py", line 23, in <module>
from .client import *
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 47, in <module>
import aiohttp
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\__init__.py", line 6, in <module>
from .client import (
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 36, in <module>
from . import hdrs, http, payload
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\http.py", line 7, in <module>
from .http_parser import (
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\http_parser.py", line 29, in <module>
from .helpers import NO_EXTENSIONS, BaseTimerContext
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\helpers.py", line 732, in <module>
def ceil_timeout(delay: Optional[float]) -> async_timeout.Timeout:
AttributeError: module 'async_timeout' has no attribute 'Timeout'. Did you mean: 'timeout'?
Process finished with exit code 1```
Anyone know what this error means? happens when i start my bot
got no clue where to even start to debug
do you happen to have a file called async_timeout?
nope
theres a file called timeout.py
how can i make my bot delete messages over 4 lines?
like the message is 4 lines long or its 4 separate messages?
oh i read that wrong
it was probably me lmao
i dont know if thats detectable personally only because my thought is the fact that on mobile it could be 10 lines while on a small monitor it could be 3 and a big monitor 1
( in the same message that is )
but you could do something like
if len(message chars) > 20
Anyone know how I can save a attachment as a variable? Like if a user sends an attachment, I want to save that attachment image as a variable to use later. Idk why but I really cannot figure this one out :/
get the attachment url and store that.
I don't think that'll work because I'm going to use the image with pytesseract next. I want the image to be able to be used like that later
then you would have to save the image locally
yeah pretty much, idk how to do it tho
what bot lib are you using
wdym
hoi!
How would I make it so a bot selects a random amount of people from a server, and gives them a role
!d random.choices
random.choices(population, weights=None, *, cum_weights=None, k=1)```
Return a *k* sized list of elements chosen from the *population* with replacement. If the *population* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
If a *weights* sequence is specified, selections are made according to the relative weights. Alternatively, if a *cum\_weights* sequence is given, the selections are made according to the cumulative weights (perhaps computed using [`itertools.accumulate()`](https://docs.python.org/3/library/itertools.html#itertools.accumulate "itertools.accumulate")). For example, the relative weights `[10, 5, 30, 5]` are equivalent to the cumulative weights `[10, 15, 45, 50]`. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
!d discord.Guild.members
property members```
A list of members that belong to this guild.
!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/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
those are the 3 things you need
I dont understand random choices
I dont get what it means by the eights and cum_weights
It picks k random elements from from a list population
you don't need those unless you want to provide specific weights & cumulative weights
So if i had a list named "hello" with [1, 3, 5]
if i did random.choices(hello, k=2)
it would pick 2 of those
right
what would i do after then? like it picked random choices, but how would i call them
it returns a new list
You can do whatever you want with that
In your case, loop over all of them and add_roles
So population is now the random choices instead of all the values?
No, it returns a completely new list
Called what?
whatever you want
How would i choose the name, im so confused
my_list = [1, 3, 5]
new_list = random.choices(my_list, k=2)
here it would be new_list
sorry i explained that pretty badly
what does this mean?
I think it explains more than enough
property members of a discord.Guild instance, which returns a sequence of discord.Member instances
a list of members that belong to this guild
All you need to know, really
this returns a list of members from the guild you then take that list and input it into random.choices
That's what I'm getting at, yes
thats why he is trying to explain to u lol. if you dont understand that then you should learn basic py
I understand the question, no worries there. I'm just trying to get them to arrive on the solution on their own instead of just me giving the solution away
no i mean that statement was meant for him lol
Ah, sorry
ive never read documents before
I learnt everything from yt vids
and i dont know what that means
oh that explains it
So random.choices(...) first argument is a list which it'll take k random items out of
You want to pass in discord.Guild.members to it
Ik random.choice
It spits out k random discord.Member instances
On which you'll iterate and apply add_roles() to
It's a 3 part solution
so 'discord.Guild.members' will give me a list of all members?
You call it on an instance, not the class
For instance (see what I did there? i'm funny), you may call it on ctx.guild
ctx.guild.members
@bot.command()
async def my_command(ctx: commands.Context, ...) -> None:
random_members: list[discord.Member] = random.choices(ctx.guild.members, k=5)
for member in random_members:
await member.add_roles(...)
here's a good starting point
I tried the docs but I still cant figure it out. Its still not saving anything
What's your code so far?
def check(m):
return m.content and m.channel == message.channel
msg = await client.wait_for('message', check=check)
async def main():
discord.Attachment.save('test', *, seek_begin=True, use_cached=False)
Yeah discord.Attachment needs to be an instance, not the class
!d discord.Message.attachments this returns a list[discord.Attachment]
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
Yo, I'm getting Command raised an exception: TypeError: 'str' object cannot be interpreted as an integer
@bot.command()
@has_permissions(administrator=True)
async def addrole(ctx, role=None, amount=None):
random_members: list[discord.Member] = random.choices(ctx.guild.members, k=amount)
for member in random_members:
await member.add_roles(role)
await ctx.send(f'Completed adding {role} role to {amount} members')``` was my code
I have intents.message_context already enabled though. If I can get the message.content fine but I cant get the attachments
amount is a string
it might be "5" for example
the attachment is part of the message
so if the message has an attachment it would be
You can use discord.py's handy typing feature:
@bot.command()
async def my_command(..., integer_argument: int) -> None:
print(type(integer_argument)) # class <'int'>
message.attachments[0] would get you the first attachment or only attachment
I think i fixed it now, but it says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'
What's the full traceback?
idk if I'm doing it right, its still not sending the attachment I send back.
heres my code rn:
def check(m):
return m.content and m.channel == message.channel
msg = await client.wait_for('message', check=check)
test=message.attachments[0]
await message.channel.send(test)
26.09 03:13:00 [Bot] Traceback (most recent call last):
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 190, in wrapped
26.09 03:13:00 [Bot] ret = await coro(*args, **kwargs)
26.09 03:13:00 [Bot] File "/./Bot2/main.py", line 170, in addrole
26.09 03:13:00 [Bot] await member.add_roles(role)
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/member.py", line 1014, in add_roles
26.09 03:13:00 [Bot] await req(guild_id, user_id, role.id, reason=reason)
26.09 03:13:00 [Bot] AttributeError: 'str' object has no attribute 'id'
26.09 03:13:00 [Bot] The above exception was the direct cause of the following exception:
26.09 03:13:00 [Bot] Traceback (most recent call last):
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 1347, in invoke
26.09 03:13:00 [Bot] await ctx.command.invoke(ctx)
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 986, in invoke
26.09 03:13:00 [Bot] await injected(*ctx.args, **ctx.kwargs) # type: ignore
26.09 03:13:00 [Bot] File "/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 199, in wrapped
26.09 03:13:00 [Bot] raise CommandInvokeError(exc) from exc
26.09 03:13:00 [Bot] discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'id'
your role object is a string
You need to use .to_file on the Attachment instance, then pass in the File instance to .send()
Good catch, didn't see that
also you actually need a message object you cant just pass message
so then i can do "-addrole @role (number)" and it'll work?
you an keep how you have it
oh shit
ur using ctx cmds lol
Yeah. Having an Attachment instance implies you have a message instance
Yeah?
this should still work
im not familiar wiht chat cmds but i assume if you mention the role and have role: discord.Role in the function it should work right?
Yes, will it get rate limited?
Depending on how large k is
i did 500, but im wondering how i can make it so it wont get rate limited no matter how big
yeah it just depends on the amount of members you are adding roles too
i read the rate limit was 10k / 10 minutes?
You can't
You need to abide by the ratelimits
I'd probably add an asyncio.sleep() to not get ratelimited
Sure, set it 2 seconds to be safe
well with adding roles it just queues up the rest
if you are ratelimited. so it will add them it just may take time depending on how many members your adding roles to
better not to get ratelimited in the first place
I've seen plenty of people getting ratelimited with the library
Though you're right, it is built in
for adding roles you don't get rate limited. the lib handles the limit and just queues up the rest.
so technically you do and you dont lmao.
Yeah. If you'd like, add a delay between each request. You don't have to
So this code works, but how would I save just the attachment as a variable ?
await message.channel.send(file=await msg.attachments[0].to_file())
image = await msg.attachments[0].to_file()
If I use this it just sends the token of it. Like <discord.File object at...>. This is what Im doing :
image = await msg.attachments[0].to_file()
await message.channel.send(image)
you need to await message.channel.send(file = image)
No? all public endpoints have per endpoint dynamic ratelimits?
the dpy library handles it tho
and when it is supposed to get rate limited it will just queue the rest
That doesnt mean you dont get ratelimited?
so technically you do and you dont lmao.
Quite contradicting
not really lol
dont be weird
hey!
Im trying to make a afk comamdn
I want it so if someone pings them while they are afk it returns a message
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How?
How is correcting a statement "weird"?
??
the discussion ended and you dont get rate limited on your end. again the library handles all of that, if you was just straight up using endpoints and such then yes you would have to worry about it
wrong reply lol. but just check if the members status is idle and return a message if so
ive got a file where i shows if a user is afk but i want it so if a person pings anyone it checks to see if that user is afk and return a message
use the on_message event and if that message contains a mention then do so
Doesn't matter, Technically you do get ratelimited on your end, your bot can get ratelimited which your bot would be your end, you just cant see it, that doesnt mean you dont?
how would i check for a mention?
message.mentions()
if message.mention()?
or like how would i do that
if message has message
Do functioon
else
pass
message.mentions() returns a list of user(s) if any
are you using dpy?
pycord
i would assume it just returns an empty list if no one is mentioned so you could
mentions = message.mentions
if not mentions:
....
how would i get the id of the person who was pinged?
iterate through mentions for the members and member.id
how though, my brain dead as fuck
Anyone know how I can use pytesserect with a file the user sends? I'm able to get the file into a varible now but it brings the "unsupported file type" error now. It works with a normal file that but it wont with the one saved from discord.
Heres my code:
image = await msg.attachments[0].to_file()
test = pytesseract.image_to_string(image)
await message.channel.send(f"***The text in the image says***:\n {test}")
you could just check if message.content contains the user id
for member in mentions:
or that
That would raise an error
if member in mentions?
try this
from PIL import Image
test = pytesseract.image_to_string(Image.open(image))
@silk fulcrum
PIL is dead isnt it?
idk lmao. thats one the examples for the pytesseract lib he is using lol
would i add member.id?
yea thats why i said idk if it returns an empty list or not. docs don't mention anything so would have to just try
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
That has no relation with the issue
an empty list returns false
Its an attribute not a method, you cant call it as it would raise list object is not a callable blah blah blah
fixed it
oh he called it bruh
what does if not mentions: ... mean tho? Are you trying to do something if there are no mentions?
I can't imagine a reason to need that
if not mentions: literally checks if a list is empty
or that ... means end the process?
!e
if not []:
print(1)
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
:lmao:
its syntax is
if True:
...
if not True:
...
heres what i have
mentions = message.mentions()
for member in mentions:
id = member.id
with open('assets/afk/afkusers.json', 'r') as f:
afk = json.load(f)
if not afk in afk:
pass
await ctx.respond("This user is afk! Please wait.")
it returns this
TypeError: 'list' object is not callable
yeeee
that's what you were typing
dat it>
dude, you are not even using member in that for loop, and you are also looping reading the json file
then what do i d
im lost
wtf
he is checking for afk members in a message
if message contains a mention and that member is afk then do stuff
that if not afk in afk: pass does just literally nothing
if any(m.id in afk_list for m in mentions)
will check if any user that is mentioned is afk
if you need to know which user(s) is(are), then you would need a loop
how would i define m or member
wdym
if any(m.id in afk_list for m in mentions):
await ctx.respond("This user is afk! Please wait.")```from you previous code ig this is what you wnat
cause in the json file
its id and if they are afk or not
so i nedd to get if there is a mention in a message, and the mentioned persons id
how does it look like?
the .json?
yes
{
234598765432: "afk",
345987656787: "not afk",
}``` like this?
{"755155481458114630": {"afkstatus": 0}}
somewhat
does the same thing
if they go afk it changes the 0 to a 1
ok
and when they get mentiond, it looks to see if they are afk
if any(afk_list[str(m.id)]["afkstatus"] == 1 for m in mentions):
await ctx.respond("This user is afk! Please wait.")```then it would be this
(afk_list is the content you read from json)
JSON objects cant have ints as keys
sad
Nice statement
im just so addicted to databases
Have you tried surreal db already
How do I use an if statement to check if the author is my bot owner? I tried this but it didnāt work:
if not ctx.author.is_owner():
return await ctx.send("not owner")
else:
await ctx.send("owner")
already answered in other server
hello
bot = commands.Bot(command_prefix='>', intents = discord.Intents.message_content, discord.Intents.message_content = True)
why this Intents arent possible to do so?
Intents = discord.Intents.default()
Intents.message_content = True
and if i want in 1 line?
god youre so unorganized
i dont think its possible
unless
discord.Intents.default().message_content = True
thats legit an unorganized mess
(intents:=discord.Intents.default()).message_content = True
bot = Bot(..., intents = intents)
``` maybe
still the same prob exist bruh
then idk
cuz you've written same
?
I copied paste
ok, but initially why were you using it?
to make a discord bot
boost bot
bot = commands.Bot(command_prefix="!", intents=intents)
replace
thenks
solved that one
pasted off github?
yeah lol
well then it might not work
I'm beginner
idk much about python
I'm just learning
ok
oops-
@slate swancan you please tell me why this attribute error comes often
pip install -U git+https://github.com/Pycord-Development/pycord
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API
If your goal is to learn python, I don't recommend starting from discord bots, that's way too complicated thing for beginners
how do i make it that my sends exactly what someone says
its a varation of on message right?
Listen for on_message and resend the message.content?
intents = setattr((intents:=discord.Intents.default()), 'message_content', True) or intents
Or Intents._from_value(...)
Traceback (most recent call last):
File "main.py", line 11, in <module>
bot = discord.Bot(intents=discord.Intents.all())
AttributeError: module 'discord' has no attribute 'Bot'
who can help ?
which wrapper are you using?
(py-cord, discord.py, etc)
can you run pip show py-cord?
its work done u just need to do pip install git+https://github.com/Pycord-Development/pycord
thx
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
cursor = self.client.db.cursor()
cursor.execute(f"SELECT * FROM afk WHERE user_id = {message.author.id} AND guild_id = {message.guild.id}")
result = cursor.fetchone()
if message.author.id in result[0]:
cursor.execute(f"DELETE FROM afk WHERE user_id = {message.author.id} AND guild_id = {message.guild.id}")
await message.channel.send(f"**{message.author.name}#{message.author.discriminator}**, You are no longer AFK.")
self.client.db.commit()
for result in cursor:
member = discord.utils.get(message.guild.members, id=result[0])
if(message.reference and member ==(await message.channel.fetch_message(message.reference.message_id)).author) or member in message.raw_mentions:
await message.reply(f"**{member.name}#{member.discriminator}** is AFK from (<t:{result[3]}>)")
```
where is the problem
Guys i have this named tupleuser(item=[(12345,"hi),(12345,"hi"),(12345,"hi")])
How can I display the name"hi" in the embed and how many times it is in list or tuple?
nothing happens
@ionic edge i have once made a afk comamnd do you want see it and have some idea?
sqlite
He is using sqlite3 and doing big mistake he is using f string in the query
yes
try something like that
@ionic edge don't use f string in the query
async with aiosqlite.connect(f'your database') as db:
async with db.execute("SELECT * FROM afk WHERE user_id = ? AND guild_id = ?", (message.author.id,message.guild.id,)) as cursor:
result = await cursor.fetchone()
Ye place holder is correct way
this is the async wait using aiosqlite
can you show me your command
if you have connect your db, you dont need the first line
2 mins
am, i think you must learn, is better to know what you do
@ionic edge https://paste.pythondiscord.com/zopibedapo
And don't use f string in the SQL query use place holder
You can search google for it
Don't think i am saying you to copy my comamnd code
Just get some idea from it
Implement your own
Do you have the correct intents?
@rugged shadow bro yesterday you helped me at level system but their's problem in that
yes
ok
Dont use f strings when working with databases
In the query
wdym?
i have json file with TOKEN
i want to use the TOKEN from another JSON file
import 'config.json' says its wrong
If I wanted to make a bot that when a message is sent, a week later or checks if it has 5 reactions
How would I go about doing that? Wouldn't waiting that long halt everything? Is AsyncIo the way to go?
not really, I mean particularly yes, but not in the way you think
the best way would be to save dates when a message should be checked in a database and have a task running to check if a date has passed and then check the message
because with asyncio.sleep(), you're gonna lose a week of data after every restart
give it a default value
async def clear(ctx, num: int = None):
an maybe move that purge statement into an else statement
Otherwise you might end up with errors or unwanted behavior
hi
Hi
how to create it ??
just put a return inside the if and shift
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
The annotation of num isnt correct
it's num: int | None = None
What if he only wanted to give it a default value and didn't really wanted to give it a None annotation in the first place? š
Hmm, just discovered something from bringing this up actually
https://github.com/Rapptz/discord.py/blob/7b595fb052c82de1fca8b89d6aacc908f1978a31/discord/ext/commands/core.py#L686-L690
discord/ext/commands/core.py lines 686 to 690
if param.required:
if self._is_typing_optional(param.annotation):
return None
if hasattr(converter, '__commands_is_flag__') and converter._can_be_constructible():
return await converter._construct_default(ctx)```
You can typehint a parameter as Optional and it'll set it to None as default if it's not provided
Well you must be explicit differing types?
Looks like you can do it with | None as well
So that u don't have to do the ugly = None
Default values aren't ugly smh
None seems hella ugly to me to be honest ĀÆ_(ć)_/ĀÆ
So you want null?
I prefer default values to None as default values, like time: int = 5 instead of time: int = None and then using an if statement
typecheckers would swear at you for the latter
Bro
you're saying it's an int and then setting to None, wtf
Feel what I am tryna say, don't go on my code its rusty
see zeffo agrees
Rust š¦

-.-
afaik most linters dont really care
š
i had a discussion about it in #type-hinting and iirc most linters didnt care abour default values with different types and the types not being specified
pylance does !
def t(time : int = 0):
if time == 0:
...
š
That's good to know
if not time:
...
?
no
Beginner Alert
š
ok
oh hi okimii
Smh don't start this again
lmao
can somebody help me create a command for a bot
i barely know anything about python
learn it
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I guess thats her way of couping the lost of okimii, calling random people okimii
Seriously tho, you should also stop it and not comment (:
Who made this? Its horribly written
Dude
What
it was somewhere on the internet, I copied it on to my gist lol ĀÆ_(ć)_/ĀÆ
the command i am looking for is to give coins to an other user
i want to make a shop server
with its own currency
They mention learning list methods, string methods, you can just specify the user must know about encapsulation?
And most importantly which i always see is people not knowing about polymorphism
I mean, there is no harm in saying that, not everyone is as good in english as u r and many people have English as their secondary language
yeah, not everyone can spot spelling/grammar mistakes in messages two seconds after being sent
English is my secondary language kek
not everyone is as good in English as u r, so imho that gist is right in specifying it as methods rather than using those terms ĀÆ_(ć)_/ĀÆ
Not really terms, they're import principles of OOP
So if you learn OOP you should also know about them
methods are part of the oops, and that is the term people use in daily usage. They don't just go on and say encapsulation. I mean, I have never seen anyone use those terms apart from u, not even anyone from dpy server or even this server
same tbh
Encapsulation isnt methods only!
he is such an okimii š
typical
My point is, a guide is meant to be written in simple words which can be understood but anyone, even a newbie and that gist does it right.
Doesn't hurt to mention the principles of OOP so people don't forget to look up on them
I would say it's a quite nice thing to do, especially for people who want to learn about a topic
Well, to go back to your first statement, I wouldn't say it's horribly written, just not written to your high standards
From what i read, it still was poorly written
I've tried 1000 times but I don't know how can anyone send me a discord bot code where It can send 4 difrent responses to 4 difrent questions?
hello is there anyone can join on my server (im testing something, a new game) its a card game!
will if user1 == discord.Member: check if the user1 object is a member object?
I wouldnāt say thatās something anybody would just have on-hand to send you
U can simply do user1: discord.Member in the function to make user1 a Member object
yes but i realy need itr
meeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
If you need to check if itās a member object, use isinstance()
Yo no I wanna "check" if user1 is a member object not convert it
That too
dm me
Sorry, then AM2i9 told u!
!isinstance

isinstance(user1, discord.Member)
will this create a condition?
!d isinstance
isinstance(object, classinfo)```
Return `True` if the *object* argument is an instance of the *classinfo* argument, or of a (direct, indirect, or [virtual](https://docs.python.org/3/glossary.html#term-abstract-base-class)) subclass thereof. If *object* is not an object of the given type, the function always returns `False`. If *classinfo* is a tuple of type objects (or recursively, other such tuples) or a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union) of multiple types, return `True` if *object* is an instance of any of the types. If *classinfo* is not a type or tuple of types and such tuples, a [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised.
Changed in version 3.10: *classinfo* can be a [Union Type](https://docs.python.org/3/library/stdtypes.html#types-union).
It's an expression, when placed in an if statement it makes it a condition, yes
OCR Land is a theme aimed at children and adults. Entrance tickets are sold online. An adult ticket to OCR Land costs £19.99, with a child ticket costing £8.99. A booking fee of £2.50 is added to all orders. A function, ticket price(), takes the number of adult tickets and the number of child tickets as parameters. If calculates and returns the total price to be paid.
Use pseudo code to create a algorithm for the function ticket price ()
I have a welcome event...how can i make so that the bot sends message only when a user joins a specific server...not all the servers the bot is there...
that's was what I was asking
Can someone help
I am children
exenifix š wtf
.
Its an exercise so no ticketsš¦
use a conditional?
Sad
how so ?
if member.guild.id == ...: #do stuff
or do the opposite and add a return so you don't gotta worry about indentation huh
ah alr
I've tried 1000 times but I don't know how can anyone send me a discord bot code where It can send 4 difrent responses to 4 difrent questions?
1000..hm... how so accurate
1001 tbh
class Dropdown(discord.ui.Select):
def __init__(self):
options = [
for i in players_list:
discord.SelectOption(label='Donate', emoji='šø'),
]
hey i can add somehow dropdown option using loop? (i will do some changes in list so i need more/less option in my dropdown!)
You would do the loop in the view subclass
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(Dropdown())
here?
Yes
and? we hgave any code example please?
add_item() accept class right?
or i can create the option in add_item?
It takes a class
class DropdownView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(discord.SelectOption(label='Test', emoji='šø'),)
something like that? in for loop?
You need to add a Select object not SelectOption
This was correct
any code example please?, that will help me
hello I'm new to discord.py and I can't send a message with an embed can someone help me?
@bot.event
async def on_messages(message):
if message.content.lower() == 'test':
test = discord.Embed(colour=None, color=0x3498db, title='test', type='rich', url=None, description='test', timestamp=None)
await message.channel.send(embed=test)
new to python or both
there's a typo in your event name, on_messages, the extra s at the end shouldnt be there
also worth mentioning to make sure you have the message_content intent enabled in your code
class VoteMenu(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
for i in range(3):
self.add_item(discord.ui.Button(label=f"{i}", custom_id=str(i)))
now how i can use the custom_id for add an action in button?
using callback?
yup, its still with callbacks
class VoteMenu(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
for i in range(3):
self.add_item(discord.ui.Button(label=f"{i}", custom_id=str(i)))
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "1":
print("helo")
something like that?
you have to specify the callback on your button objects
in your case inheritance would be the preferred way to do so
i.e. ```py
class VoteButton(discord.ui.Button):
async def callback(...):
inside VoteMenu
self.add_item(VoteButton(label=f"{i}", ...))```
class VoteMenu(discord.ui.View):
def __init__(self):
async def callback(self, interaction: discord.Interaction):
print(self.values[0])
super().__init__(timeout=None)
for i in range(3):
self.add_item(discord.ui.Button(label=f"{i}", custom_id=str(i)))
no you'd put the callback method in a separate Button subclass as per my example
i dont got you...
there's two different classes you would have, a VoteButton and a VoteMenu
I'm new to bots, I know python but I dev with tkinter
oh okay
the VoteButton is where you'll write the async def callback, and the VoteMenu is where you'll add your three VoteButton objects
class VoteMenuButtons(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button()
async def options(self, interaction: discord.Interaction, button: discord.ui.Button):
if button.custom_id == "1":
print("hello")
class VoteMenuView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
for i in range(3):
self.add_item(discord.ui.Button(label=f"{i}", custom_id=str(i)))
oh it's good thx
can i get a good example please?
class VoteButton(ui.Button):
def __init__(self) -> None:
super().__init__(...)
async def callback(self, interaction: discord.Interaction) -> None:
...
class VoteView(ui.View):
def __init__(self) -> None:
self.add_item(VoteButton())
is this what you're looking for, from what I've inferred from your conversation
also another example similar to ashley's: ```py
class MyButton(discord.ui.Button):
async def callback(self, interaction):
await interaction.response.send_message(f'You clicked {self.label}!')
class MyView(discord.ui.View):
def init(self):
super().init()
for label in ('sharex', 'foobar2000', 'vlc'):
self.add_item(MyButton(label=label))```
see the pattern? two classes, one inheriting from Button, the other inheriting from View
i can define guild in MyView ?
sure
how?
depends on what guild you need the view to know about...?
for example if it needs to know the current guild, you might make it a parameter of init and pass it during instantiation
class MyView(discord.ui.View):
def __init__(self, guild: discord.Guild):
super().__init__()
self.guild = guild
@bot.command()
async def mycommand(ctx):
view = MyView(ctx.guild)
...```
ok i got you
this is mostly object oriented programming, whatever concepts and techniques you can use with regular classes also apply to discord.py's views
We dont spoonfeed here and you've tried 1000 times and cant figure out something as simple as that?
I would say that's an exaggeration
Okimii learning about hyperboles
I doubt hes learning about hyperboles, either way its a topic you learn in 5th grade
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem\bot.py", line 220, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem\modules\beta_features\cog.py", line 31, in repo_bug
await dev_server.send(embed=dev_embed)
AttributeError: 'NoneType' object has no attribute 'send'```
@nextcord.slash_command(name="report-bug", description="Report a Bug")
async def repo_bug(self, interaction: nextcord.Interaction, message: str = SlashOption(name="message", description="Please describe your problem or the error",
required=True, max_length=250)):
dev_server = interaction.client.get_channel("1024019062558314537")
random_id = random.randint(1_000_000_000, 9_999_999_999)
dev_embed = nextcord.Embed(title=f"Report from {interaction.guild.name}",
description=message)
dev_embed.add_field(name="Please answer tot the following ID:", value=interaction.channel.id)
dev_embed.add_field(name="Case ID", value=random_id)
await dev_server.send(embed=dev_embed)
await interaction.response.send_message(content="Thank you for your report. The team will take care of it as soon as possible and send you an answer in this channel.", ephemeral=True)
```
hello, I want to make a bot, but there is a function I don't know what it's called, this function is a message sent by the bot, and clicking on it puts a list where you can choose roles for example
I think you're speaking about "dropdown menu" or Select
nextcord.Client.get_channel is a cache lookup and may return None if the ID isnt in cache, in this case it wouldnt return anything as the ID isnt an int, i'm not sure why discord.py doesnt type convert the str type or raise a type error
@commands.slash_command()
async def timeout(self, ctx, member: disnake.Member):
await member.edit(timeout = datetime.timedelta(hours = "1"))```
fyi, all public get_* methods are cache lookups
oh okay thank you, and you know what it's called in the doc?
ThTs nextcord and not discord.py???
It still applies, but the given method is incorrectš
how do I find a ctx's role?
Well, iirc discord.py does raise a type error when conversion isn't possible
Conversion of the snowflake?
Conversion to the typehint
I'm not referring to the conversion of arguments
Then?
i'm referring to
discord.Client.get_channel
which doesnt raise a TypeError when the incorrect type is passed as an argument
Ohh wait, u meant convertung the string to type int
Yes!
Code:
def check(message):
return message.author == ctx.author and message.channel == ctx.channel and message.content.lower() == "close"```
**Question:**
How can i make it so the "close" will be the message i input and that the bot will print in the output ?
Ngl that's a mystery to me too. Probably cz Danny loves IDs as ints only and hates it when someone uses strings? Who knows š«¤
At least u can use a string type ID in fetch methods
in discord.py
discord.ui.Select if you want to use the decorator it's discord.ui.select
python works with large ints nicely, why not use it
Yeah, in this case it uses dict.get which uses the type passed
pls help š
On this note, I saw a change somewhere which changes the behavior of large ints in Python
Lemme find the link
Our apologies for the lack of transparency in the process here. The issue was first reported to a number of other security teams, and converged in the Python Security Response Team where we agreed that the correct fix was to modify the runtime. The delay between report and fix is entirely our fault. The security team is made up of volunteers, o...
This is correct. Do you know about wait_for?
@astral ether here's an example that could help you
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
yes it works but how do i make it that the "close" will be just the message i input ?
uh oke
That's correct. That if statement checks the whole message and not a part of it, so the check won't pass if u send anything other than just the word close in yr message @feral frost
ok but how do i make it so the "close" changes into the message i input
thanks
oh okay
Uh what? @primal token do you mind helping Mimmeke with their issue? I gotta crash, it's late here
if you have any question ask freely here
You mean like
message.content.lower() == message.content
```?
Doesn't that do the same thing as message.content == "close"?
ĀÆ_(ć)_/ĀÆ
I'm just confused, so correct me if I'm wrong lol
it's to add one that I don't quite understand š¦
to add it to a message
there's a kwarg to send the view as message component with a message, if that's what's you're asking
btw to send a view you need to first create a view
so in the example it create first a view with some basic things and then send it
for example for its how can I make it appear? I entered all the code and launched my bot
Hey guys I have no clue why my bot is not replying to my command, I activated all the intents within the code and on dev side. Here's the code ```
import discord
from token_bot import bot_token
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="$", description="Hey there, I'm a bot :)", intents=intents)
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"We have logged in as {client.user}")
@bot.command()
async def test(ctx, arg):
await ctx.send(arg)
'''@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith("$hello"):
await message.channel.send("Hello!")'''
client.run(bot_token) ```
have you copy pasted the example? if so you should send a message in your test server like this <bot_prefix>colour
no but i wasnt asking for that š
i was asking for this š
That expression seems a bit redundant in my opinion
not my intentions
@feral frost if you want to check if a string is all lowercase, just use islower()
message.content.islower()
ok
yes I just copied this code entirely but nothing happened
How to add a file on a webhook with requests?
$yellow for example ?
no, it's literally $colour
With requests, you can use the file argument to send a file
Yes but how would the code be?
@slate swan You'd have to do something like
request.post(url, files={"myfile.txt": open('myfile.txt', 'rb')})
But if you want to send a JSON object with other information, you need to send it with something like this, since the body will be form data
request.post(url, files={
"myfile.txt": open('myfile.txt', 'rb'),
"payload_json": (None, json.dumps(data))
})
you're welcome
theres also a few more things, such as the fact you have bot a bot and a client, you should only have one, and that you don't actually enable message content intents
Thanks
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem\bot.py", line 220, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem\modules\beta_features\cog.py", line 48, in answer_to_request
await answer_channel.send(embed=ae)
AttributeError: 'NoneType' object has no attribute 'send'```
@nextcord.slash_command(name="answer-to-request", description="Answer to a request")
async def answer_to_request(self, interaction: nextcord.Interaction, content: str = SlashOption(name="content", description="Please type here your answer",
required=True, max_length=200),
ac: int = SlashOption(name="channel_id", description="Please type here the ID from the Report Channel", required=True)):
if interaction.user.id == 881929560059428924:
answer_channel = interaction.client.get_channel(ac)
ae = nextcord.Embed(title="You got an answer from the Maja Bot Dev Team", description=f"{config.DiscordSupport} {content}")
await answer_channel.send(embed=ae)
await interaction.response.send_message(content="Your reply has been sent successfully", ephemeral=True)
else:
await interaction.response.send_message(content="You can not use this command. You are not a member of the Maja Bot Dev Team.", ephemeral=True)
```
how do I get the bot to check if the user has reacted with a certain role?
I'll look more into it, thank u!
Try commenting out that line where you use get_channel, and change the typehint of ac to discord.Channel. Looks like there is a CHANNEL option type for slash commands, so changing that typehint might get you a channel object right off the bat.
is there a way to prevent members from typing more than 3 lines with a bot?
Nope it is a id from a channel from a other server
ah, alright then
get_channel attempts to get the channel object from it's internal cache. If it's not in there, it returns None. You can fix it by doing something like this to fetch the channel with an API call if it's not in the cache
answer_channel = interaction.client.get_channel(ac) or await interaction.client.fetch_channel(ac)
if self.custom_id == "0":
embed.add_field(name=interaction.message.embeds[0].fields[0].name, value=int(interaction.message.embeds[0].fields[0].value)+1,inline=False) ## here
embed.add_field(name=interaction.message.embeds[0].fields[1].name, value=interaction.message.embeds[0].fields[1].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[2].name, value=interaction.message.embeds[0].fields[2].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[3].name, value=interaction.message.embeds[0].fields[3].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[4].name, value=interaction.message.embeds[0].fields[4].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[5].name, value=interaction.message.embeds[0].fields[5].value,inline=False)
if self.custom_id == "1":
embed.add_field(name=interaction.message.embeds[0].fields[0].name, value=interaction.message.embeds[0].fields[0].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[1].name, value=int(interaction.message.embeds[0].fields[1].value)+1,inline=False) ## here
embed.add_field(name=interaction.message.embeds[0].fields[2].name, value=interaction.message.embeds[0].fields[2].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[3].name, value=interaction.message.embeds[0].fields[3].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[4].name, value=interaction.message.embeds[0].fields[4].value,inline=False)
embed.add_field(name=interaction.message.embeds[0].fields[5].name, value=interaction.message.embeds[0].fields[5].value,inline=False)
how i can make this looks better
im trying to edit a embed value
if self.custom_id == "0": im changing the first field only
if self.custom_id == "1": im changing the second one only
i want the others fields the same, i mean if i change the first field the other 5 not change.
etc.
could do something like
n = 0 # or 1, or 2, or whatever
for i, field in interaction.message.embeds[0].fields:
value = field.value
if i == n:
value = int(field.value)
embed.add_field(name=field.name, value=value)
?
Or, if the new embed and the old one are the same except for that one value, just modify the old embed
You could delete a user's message if they have more than 3 newlines
what about this error please>?
print is not an async function, you don't need to await it
lol im stupid sry
my bad
and is there like a delay command if i want to wait a bit between print-s
Someone can help?
await asyncio.sleep(seconds)
replace seconds with an int
thankssss
I'm not a nextcord user, but answer_channel is None, could be a cache problem or something else, try to use an Api calls
Thought I gave you an answer?

The answer is incorrect
.
š¦
@wicked atlas is top š ā«
name asyncio isnt defined
What's wrong with it?
you should import asyncio
It is a id from a other server
oke
And nextcord.Channel doesnt exists
And? As long as the bot is in that server as well, it should be able to fetch that channel
And did you scroll up and see what message I was replying to, or just assumed it was my first reply?
nextcord.TextChannel returns the channel if server a not server b