#discord-bots
1 messages · Page 179 of 1
AttributeError: 'Bot' object has no attribute 'hybrid_command'
!d discord.ext.commands.Bot.hybrid_command
@hybrid_command(name=..., with_app_command=True, *args, **kwargs)```
A shortcut decorator that invokes [`hybrid_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.hybrid_command "discord.ext.commands.hybrid_command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.add_command "discord.ext.commands.Bot.add_command").
What lib you use
pycord
so its not possible to use hybrid cmds?
Too bad
Only in dpy
hmm, okay ty
alrdy installed
pip uninstall discord
discord.py not discod.py
now reinstalled discord and discord.py
remove discord
!pypi discord.py
keep only discord.py
is there any way (other than the boosting role one) to check if a member is boosting the server or not?
hybrid commands are called bridge commands in pycord
you can lookup for it in the docs
!d discord.Member.premium_since
An aware datetime object that specifies the date and time in UTC when the member used their “Nitro boost” on the guild, if available. This could be None.
it will be None if the user is not boosting right?
also
this is soo much pain
how to test this thing, i dont wanna boost and unboost like a million times
Read the embed, that's the answer
This could be None
could be..
when member is not boosting?
Just ask it
discord.py doesnt automatically convert member argument of the function to a member object, no?
try to implement a kick by id thing first
@client.command()
async def kick(ctx):
user = ctx.guild.get_member(<user id>)
await user.kick(reason=None)
also you can try
member: commands.MemberConverter
instead of member: discord.Member
(you need to from discord.ext import commands first)
also why would you even do this
async def kick(ctx, member:discord.Member, reason=None):
if reason == None:
reason='No reason given'
just do reason='No reason given', no?
you are not in #esoteric-python ?
why would you make your bot's code obfuscated?
you dont apply esoteric stuff to something like bot's code if it doesnt help you 🤷
how is setting a default string value for a function argument less readable than setting it to None and then having an if statement
my bot dont send server messages but private he send
yeah sure let me use
euler = lambda steps: __builtins__.sum([(0^1 & (0 | 1))/(__import__(name=(__import__('base64').b64decode("bWF0aA==").decode('utf-8'))).factorial(_)) for _ in __builtins__.iter(__builtins__.range(steps))])
instead of a mathematical constant
no, its just the fact that i dont know how to do funky code
show some code
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="=", intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send("lol xd bruh nice")
@bot.event
async def on_ready():
await bot.change_presence(
activity=discord.Streaming(name="Play in the Code", url=""))
print('Bot is Online')
bot.run("+++++++++++++")```
It does 🤨
If you type hint it in the command parameters/arguments
!e
exec(dir(__builtins__)[dir(__builtins__).index('print')]+'("idk")')
@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.
idk
Ew, exec
yeah i said it later
ehh i dont really think there's another way to execute some command from its name as a string
you can but that won't be the correct typehint for your type checker and language server
eval
i mean exec and eval in this case are basically the same, no?
kinda, yeah
but eval isn't capable of performing imports and stuff iirc
!e
getattr(__builtins__, "print")("meow")
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
meow
i think you can do dunder imports with eval?
!e ```py
eval("import this")
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1
004 | import this
005 | ^^^^^^
006 | SyntaxError: invalid syntax
If you don't count getattr then I guess
yeah they work
!e
eval(__import__('this'))
@lyric sphinx :x: Your 3.11 eval job has completed with return code 1.
001 | The Zen of Python, by Tim Peters
002 |
003 | Beautiful is better than ugly.
004 | Explicit is better than implicit.
005 | Simple is better than complex.
006 | Complex is better than complicated.
007 | Flat is better than nested.
008 | Sparse is better than dense.
009 | Readability counts.
010 | Special cases aren't special enough to break the rules.
011 | Although practicality beats purity.
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/apupuyafop.txt?noredirect
oh yeah this is another way, thanks for reminding
isnt it a part of globals too lol
!e
getattr(__builtins__, dir(__builtins__)[dir(__builtins__).index('print')])("test")
@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.
test
!e globals()["print"]
🤷
yeah true
Pins
what's a slash menu 🤔
async def roles(interaction: discord.Interaction):
select = Select(options= [
discord.SelectOption(label="Quant",emoji="🦴",description="The great programming language"),
discord.SelectOption(label="Bitcoin",emoji="🦴",description="Nice programming language"),
discord.SelectOption(label="Etherum",emoji="🦴",description="Nice programming language"),
discord.SelectOption(label="Solana",emoji="🦴",description="Nice programming language")
])
view = View()
view.add_item(select)
await interaction.response.send_message("role bar: ", view=view)
how do i append role when sb chooses for example quant?
thx
whats the error
the code is correct, and you didnt send what the error is
wait..
Genius
sry
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.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
did you try reading it
still isnt it
description = "ur description" in the slash_command decorator
what?
doesnt help me
the callback inside it gets triggered when the select is used.... you need to override it to make it do what you want
code?
.
He just told you how
Can you give me an example
Or the code?
description is a key word argument in slash_command just provide it's value?
Okay Thanks
name="command", description="hello"
Thanks
Also i recommend reading docs
Ok
is there a solution to avoid falling several times on the same image with random.choice(image)?
i have 20 images*
maybe remove the image from the list?
secrets.choice(sequence)```
Return a randomly chosen element from a non-empty sequence.
i see, its ""pseudo-random""
@slate swan what is the difference with random.choice and sercet.choice?
the secrets module is much more cryptographically safer than random to work with
and so is the .choice func
@slate swan can i add role by interaction.user.add_role()?
How can I improve the performance of this code to retrieve data from the database more quickly?
summoner = collection.find_one({"discord_id": member.id})
if summoner:
summoner_id = summoner.get("summoner_id")
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier = summoner.get("tier")
rank = summoner.get("rank")
elo = summoner.get("elo_rating")
users.append({"member": member, "summoner_name": summoner_name, "tier": tier, "rank": rank, "elo_rating": elo})```
ok, but to choose images from a folder (embed with image with !hello command)? can I add a parameter to my existing command to say that I don't want the same image twice in a row?
yes sir
i'll write an example and ping you in #bot-commands in a minute
well for the db part idk but you can improve your code a lot using a dataclass, are the keys always same?
!d random.sample
random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
No
Any disnake users here?
@bot.slash_command(name='test', description='description')
async def test(inter):
embed = disnake.Embed(
title="Embed Title",
description="Embed Description",
color=disnake.Colour.yellow(),
url="https://disnake.dev/",
timestamp=datetime.datetime.now(),
)
embed.set_author(
name="Embed Author",
url="https://disnake.dev/",
icon_url="https://disnake.dev/assets/disnake-logo.png",
)
embed.set_thumbnail(url="https://disnake.dev/assets/disnake-logo.png")
embed.set_image(url="https://disnake.dev/assets/disnake-thin-banner.png")
embed.add_field(name="Regular Title", value="Regular Value", inline=False)
embed.add_field(name="Inline Title", value="Inline Value", inline=True)
embed.add_field(name="Inline Title", value="Inline Value", inline=True)
embed.add_field(name="Inline Title", value="Inline Value", inline=True)
embed.set_footer(
text="Embed Footer",
icon_url="https://disnake.dev/assets/disnake-logo.png",
)
await inter.response.send_message(embed=embed)
why does this not work?
well there are no errors in the terminal, it just sends an app is not responding error
oh, ok, seems like it is an error that happens due to me trying to make the bot controlled both by a terminal and slash commands
Yep, fixed now
How could i implement a terminal-controlled stuff in my bot without breaking slash commands?
Threading
how would i interact with the bot object from 1st thread inside the 2nd thread?
!e
import threading
import queue
import time
jobs = queue.Queue()
def command_worker():
while True:
print("Working on:", jobs.get())
m = threading.Thread(target=command_worker, daemon=True)
m.start()
jobs.put_nowait("sync")
time.sleep(3)
jobs.put_nowait("reload")
time.sleep(0.1)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Working on: sync
002 | Working on: reload
Does someone know a free provider for hosting my discord bot?
I used heroku but it isn't free anymore
So I have a modal, the modal has 2 textinputs.
This modal is sent when a user clicks a button.
If any of the text inputs are filled in it updates an embed.
I want it so once the textinput has been submitted, it changed the button style of the button it was sent from.
could someone give me the piece of code to add to send an emoji on the embed that my bot sends in the command.
the "await ctx.message.add_reaction("\U0001F60E)" command sends an emoji on the message from which the member's command is sent. but I can't assign it to the embed instead
Store the message that your bot sent then add the reaction to it
what do you mean by "store"?
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
The method returns the sent message, store it in a variable
@bot.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, id="1063812548924813397")
await bot.add_roles(member, role)
is supposed to give members a role upon joining but it just doesnt, no errors nothing
just doesnt give it to em
The guild that the member belongs to.
sent_message = channel.send(content="My message")
print(sent_message.id)```
is correct?
my bad man
Await the channel.send
im really new to python and discord.py, i just replace member.server with discord.Member right?
No, member is an instance of discord.Member
You should have basic OOP knowledge to be more comfortable with discord.py
im not trying to make a fully fledged bot, just one that stays online and gives members a role once they join
what? 😕
idu, sorry
is not very clear for me ^^
msg = await channel.send(...)
await msg.add_reaction(...)
i dont get it
Yea but you need to know OOP to make any kind of bot with discord.py even if its not one with a lot of features
but i really dont need it for anything else so i dont see the purpose of learning an entire programming language to create 1 feature
good luck finding someone to spoonfedd you then
is there any hosts like heroku to host my bot?
well theres replit and ur pc
replit? all repl's are gonna be public and so will my token
you can hide your token in replit
how?
Ok, so for the last few days I've seen quite a lot of questions in the ask space about hiding Discord Bot Tokens or other secrets now that the replit env's are gone.
A lot of people are panicking because their bots aren't working and they are afraid that they aren't going to be able to keep their token secret, but replit has already given out t...
your code will be public
but not your token
There's most likely an error handler that ate your error
A wait nvm
Yeah i guess there was something to do with stuff in my on ready function because it started working when i removed it
i was trying to create a command that'd send an embed with latest homework btw, works perfectly now
👀 isnt this kinda pog
channel is not defined
i tried with ```py
newmsg= await message.channel.send(embed_msg)
await newmsg.add_reaction("\U0001F60E")
same probleme...
wtf
man wtf
!tempban 398556306832752642 14d Not sure what that was but it definitely wasn't appropriate for here
:incoming_envelope: :ok_hand: applied ban to @lucid wadi until <t:1675005746:f> (14 days).
code - https://pastebin.com/xh0RU7GC
error - 'init' of 'super' object needs an argument
can you guys please help on this error , framework = nextcord
please send the full traceback
-
Ignoring exception in command <nextcord.application_command.SlashApplicationCommand object at 0x7f3b859893a0>:
Traceback (most recent call last):
File "/home/jaiyesh/.local/lib/python3.9/site-packages/nextcord/application_command.py", line 906, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "/home/jaiyesh/development/discord.bot/shadow.py", line 185, in image_gen
return await msg.edit(content="Content Generated by **craiyon.com**" , file=nextcord.File(image , "image.png") , view = DropdownView(msg , images , interaction.user.id))
File "/home/jaiyesh/development/discord.bot/shadow.py", line 175, in __init__
self.add_item(Dropdown(self.message , self.images , self.user))
File "/home/jaiyesh/development/discord.bot/shadow.py", line 156, in __init__
super.__init__(
TypeError: descriptor '__init__' of 'super' object needs an argument
The above exception was the direct cause of the following exception:
nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: descriptor '__init__' of 'super' object needs an argument
Do anyone know how can I get an friend request link?
like an discord server link that you can click to join but click to add friend
thank you so much and why is () required just asking
super is a class, you need to instantiate it
i see
https://docs.python.org/3/library/functions.html#super bit more detailed info
Should I use await for this code?
tier = await summoner.get("tier")
rank = await summoner.get("rank")
elo = await summoner.get("elo_rating")```
summoner = collection.find_one({"discord_id": member.id})
if summoner:
summoner_id = summoner.get("summoner_id")
summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
tier = summoner.get("tier")
rank = summoner.get("rank")
elo = summoner.get("elo_rating")
users.append({"member": member, "summoner_name": summoner_name, "tier": tier, "rank": rank, "elo_rating": elo})
else:
not_in_database.append(member.mention)```
Or should I just keep it as it is?
Hello everyone
how i can fix this?
im using slash commands
trying to know if the bot is connected to voice chat
can I have a command that has a space in it? 
such as
+string1 string2?
Command group
What's the problem then
is_connected is not working
can't I have it as it's own command? 
obviously with having an on_message_send that check + string1 string
hey i need help, how do i get the bot to send me the answer pricvat when i send a message in the server?
async def esport(ctx):
embed = discord.Embed(title="E-Sport", description="gg", color=0xf95757)
embed.set_thumbnail(url="")
embed.set_author(name="gg")
embed.add_field(name="hh", value="hh", inline=False)
embed.set_footer(text="th")
embed.set_image(url="")
await ctx.respond(embed=embed)```
Does someone know a free provider for hosting my discord bot?
I used heroku but it isn't free anymore
nope, I self host it on my laptop lOl
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
thank you Zeffo
Hello
does ctx still work for yall, for some reason it doesnt for me?
async def on_message(message):
if(message.channel.id == '1059977737000992799'):
if(message.content != "!verify"):
await message.delete()```
Why bot isn't responding to anything after i added this to my code
is that the right channel id?
works fine
Yep
and is the bot capable of viewing that channel?
Yes it has administrator perms
did you declare youre intents on message content
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Client(intents=intents)
To be able to read message content now requires you to declare your intent
ID1=1059977737000992799
if(message.channel.id == ID1):```
I did ID1 = "1059977737000992799"
And if(message.chabnel.id == 'ID1'):
just uh.. just copy what I threw for ya?
its even youre channel id already but no you do not need quotes
and since youre referencing a variable you do not need singles around your var name
so just
ID1(your varname) = 1059977737000992799(your channel id)
then if(message.channel.id = ID1(your varname))
then you would need to post the code for !verify? this is all youve posted
async def verify(ctx):
await ctx.send('Sent verification info. Please check your DMs.')
await ctx.author.send(embed=main)
time.sleep(3)
await ctx.channel.purge()
@client.event
async def on_message(message):
if(message.channel.id == ID1):
if(message.content != "!verify"):
await message.delete()
client.run(os.environ['token'])
keep_alive()```
Sent
also you should swap that time.sleep for asyncio.sleep
!d asyncio.sleep
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
Do anyone know how can I get an friend request link?
like an discord server link that you can click to join but click to add friend
?
?
What did u send
Read the URL link would have told you that
U think
await bot.process_commands(message)
This i guess?
Idk there is bunch of text that has nothing to do with my problem
your problem is that the verify command isn't working, right?
the link explains how to solve that
Which part in the link
it provides two solutions, you can use any one
There's alot kf solutions for other problems
await bot.process_commands(message)
By adding this
async def on_message(message):
if(message.channel.id == ID1):
if(message.content != "!verify"):
await message.delete()
await bot.process_commands(message)```
Not it
Lemme try another one
hey i made a web scraper and i wanted to connect itnwith my dc bot any idea how to make it since i dont know how to start
just a simple !scrape command and then where i have to input the product info which gets send to my scraper
Didn't work bot still not responding to !verify
so i dont have to go everytime i want to scrape something in my python file yk ?
Well yeah it wasn't coded to respond to !verify
If the message is anything but !verify, delete the message and process command
How to code it to respond to!verify
Do you have a command handler?
Reaction is harder to bypass.
Check dm Boss
from discord_components import SelectOption
ModuleNotFoundError: No module named 'discord_components'
Please use discord.py, That module is really old.
how would i do that
u do pip install discord.py
use the app_command from discord.
ik but how do i make the drop down
and get SelectOption from discord.SelectOption
U need to make a select class and then add it to a view.
ok
@hollow gazelle tho, ur select even when disabled needs to have a selectoption
ok
@client.command()
async def verify(ctx):
await ctx.send('Sent verification info. Please check your DMs.')
await ctx.author.send(embed=main)
time.sleep(3)
await ctx.channel.purge()
how to use an emoji as parameter ?
An emoji isn't a param
You can prolly make emoji as arg but use type hint string instead of .emoji
str ?
Yea
!d discord.Emoji
class discord.Emoji```
Represents a custom emoji.
Depending on the way this object was created, some of the attributes can have a value of `None`...
class discord.app_commands.Transformer```
The base class that allows a type annotation in an application command parameter to map into a [`AppCommandOptionType`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType "discord.AppCommandOptionType") and transform the raw value into one from this type.
This class is customisable through the overriding of methods and properties in the class and by using it as the second type parameter of the [`Transform`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transform "discord.app_commands.Transform") class. For example, to convert a string into a custom pair type:
how
async def on_message(message):
if(message.channel.id == ID1):
if(message.content != "!verify"):
await message.delete()
else:
async def verify(ctx):
await ctx.send('Sent verification info. Please check your DMs.')
await ctx.author.send(embed=main)```
Why isn't this working
what do you expect this to do?
To delete every message except !verify and !verify is command that sends embedded message in dms
have you read about how commands are written?
Mhm
Maybe
I had command written already before but because of on_message event bot didn't want to respond to command
Exactly what zeffo gave to me
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
how you ACTUALLY write commands
and you didn't read it? or...
And i did this
that process command shit shouldn't be in your if statement
get it out and all will work fine
anyways, you should read this instead, you don't want to write commands through on_message, that'll be a pain in the ass once you add arguments / options to your command
like !shit <user>
Hmm how to get it out it still gives error
I knew that already
is this right ?
but you didn't do it?
I have a question, if I have a button that when u press it, it sends the same button again and disables the last one, how would I make the new button that is sent to have a new label?
ofc you can, at least show what you tried
just saying "it doesn't work" is not the way you'll get help
async def on_message(message):
if(message.channel.id == ID1):
if(message.content != "!verify"):
await message.delete()
await bot.process_commands(message)```
probably has something to do with button.label = ...
idk, I don't use v2 stuff
Use an if statement to check if it was pressed then make a new button within it
How do i get it out of if statemnt?
that's not even in your on_message event anymore
Accidentally spaced down
are you even using an IDE?
like vscode or whatever
😭
looks something like this
I tried that, but it didnt work I think because that's for the current button that soemone presses
i'd edit original response which will only edit hte one that i just clicked idk how to edit for the future button sent
"rename a button" ctrl+F that in this chat and you'll most likely find people here who have asked a similar question
I don’t use much v2 so I don’t know off the top of my head
okay ty
async def on_message(message):
if(message.channel.id == ID1):
if(message.content != "!verify"):
await message.delete()
await bot.process_commands(message)```
I did this one not the last one
What’re you trying to do?
to make bot still respond to command and deletes everything else but not the !verify
Like it deletes now but it won't respond to !verify
are you using notepad to write code? this isn't indented like you'd normally do it
Yep
that's because that's not even in your code... 🧠
why don't you use an IDE? lol
What's not in my code?
Command !verify
Use VSCode or Sublime text at the very least
that it should respond
I'm on phone using replit
async def verify(ctx):
await ctx.send('Sent verification info. Please check your DMs.')
await ctx.author.send(embed=main)
time.sleep(3)
await ctx.channel.purge()```
This is code for command
Use asyncio.sleep, time.sleep is blocking
^^
time.sleep worked fine but anyways I'll change it
What’s the issue with this then?
It still isn't the problem
it is
There's issue with on message event
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
most likely, you have other errors in your code going on
Do you understand the basics of python?
I highly suggest you to first of all step away from using notepad as a code editor
especially as a beginner
I said I'm using replit
^^
↑↑
Replit is not recommended either
Still works
Bruh from helping me fix the got we got to recommendations
Just help me fix this I'm stupid asf
.
We’re trying to help you from potential issues as well
there's more errors in your code you're not showing
line 50
your process_commands is STILL in an if statement
Idk how to get it out
I admit
@potent spear not sure if we should be helping he quite literally has a variable named phish
Phish is litteraly just redirecting to another side instead of one that's shown in hyperlink
I could just remove it if I didn't want you to see
But i don't have anything to hide it's safe code so I didn't remove it
if (shit)
print("in the if statement")
print("still inside")
print("out of the if statement")```
The phish variable value isn’t seen in the code which is what made me think it’s something malicious
Because you purposely removed it
Ye i guess that's valid reason to be suspicious
^^
await bot.process_commands(message)```
Ah no spaces
!indent
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
read that ^
try and see, you'll get the hang of how indentation works if you read what I told you to
That’s the best way to learn it ^
having an actual code editor will help you massively
in that case, you don't even have to care if it's a space or a tab, because the code editor formats it FOR YOU
look above or under that line of code, there's most likely more to it
There is format button in replit
well, make great use of that
make sure to actually have read this
that line in your error should be indented one level
in your case, it's indented three levels
it's not ALIGNED with the outer most if statement, meaning it shouldn't be in any
if that's how it turned out, replit's formatting sucks
yes, your line of code is inside the second if statement, you can SEE the difference, if you still don't understand, there are more info links in that bot's message
Here? bot.process_commands(message)
Where i typed here? I need to delete intends
Behind that code
I did all possible combinations
yeah, that line is incorrectly indented, as mentioned for the 100th time
I ran it after deleting every single intend
you did not, just read about it, you'll find out, you're blindly guessing
And none worked
it should be indented one level, not zero
don't come back unless you've either fixed it or read all the links the bot told you to
Lmao
Litteraly skull
Jit i deleted some intends bot ran and still command not working
OHHH
LMAOOOOO I SEEE
YESSIR I FIXED IT
I mean yall helped tysm
At the end i got intends right but bot.process_commands(message) wasn't right because i use client.command not bot.command didn't define bot
indents
should've given you an obvious error that client wasn't defined anyways
Idrc about that sorry
you should
Should've notice it when i gave you full code? 
How do i stack more exceptions?
Like if(message.content != "!verify","Sent verification info. Please check your DMs."):
full code was perfectly fine except you indentation on line 50...
https://paste.pythondiscord.com/itefarodab.py
Ye okay
that's not what those are called
that's not how you write commands, you should know by now
?tags
!tags
» traceback
» type-hint
» under
» underscore
» venv
» virtualenv
» voice-verification
» windows-path
» with
» xy-problem
» ytdl
» zip
@client.event
async def on_member_remove(member):
Is this how I would check if a user has left the server? or does it have to be @client.listen()
either work
note that you'll need member intents for this
listeners are preferred
intents = discord.Intents().all()
I have this
mhm, make sure it's all enabled in dev portal too
yeah it is yepyep
👍
^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'avatar_url'
File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 82, in on_member_join
embed.set_author(name=member.name, icon_url=member.avatar_url)
^^^^^^^^^^^^^^^^^
AttributeError: 'Member' object has no attribute 'avatar_url'
thats full error
member.avatar.url
i had that
File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 82, in on_member_join
embed.set_author(name=member.name, icon_url=member.avatar.url)
Thats not an error code
holdon
Holding
raise e
File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 82, in on_member_join
embed.set_author(name=member.name, icon_url=member.avatar.url)
^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'url'
did.. did you define member?
ye
can you post your code?
The member doesn't have a profile picture
member.display_avatar.url should be failsafe
ok
what does it return for a default avatar?
the default avatar
in the correct color too?
yes
the color of the default avatar depends on your discrim % 5
discord.py handles that for you
good to know
it worked
What is a "topic"?
!d discord.Message.create_thread
await create_thread(*, name, auto_archive_duration=..., slowmode_delay=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a public thread from this message.
You must have [`create_public_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.create_public_threads "discord.Permissions.create_public_threads") in order to create a public thread from a message.
The channel this message belongs in must be a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel").
New in version 2.0.
!d discord.Message.pin
you already know how commands work?
await pin(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Pins the message.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this in a non-private channel context.
Yes
F, my guy is creating his own wrapper
you're not using any python library for writing a bot?
I can create a discord bot very easily
But there is a problem with "thread"
Ignoring exception in on_member_join
Traceback (most recent call last):
File "C:\Users\rhino\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 89, in on_member_join
raise e
File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 87, in on_member_join
raise e
File "C:\Users\rhino\OneDrive\Desktop\evolve\main.py", line 84, in on_member_join
embed.set_footer("Evolve Devlopment")
TypeError: Embed.set_footer() takes 1 positional argument but 2 were given
then why are you showing a request? where's your actual code?
text='Evolve ...'
oh
^^^^
is it same for thumbnail just with url='link'
you're not using discord py though... 🤔
import requests
for that, you can check the docs and know what positional arguments vs kwargs are
ok
You must be on an older version of discord.py
yes
What is code for mention author
py -3 -m pip -U install discord.py I believe is the command
message.author.mention
await ctx.send('Sent verification info. Please check your DMs. message.author.mention')
This would work?
nope
ctx.author.mention ?
alr
!fstring
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Sure
Oh ye i remember
Ok
Ty
await ctx.send(f"Sent verification info. Please check your ctx.author.mention")
Doesn't work
{}
{ctx.author.mention}
await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
Ty
Hello guys, I have a question....Can I get a project from the famous bots?
Like a probot
Error:
await ctx.send(f"Sent verification info. Please check your ctx.author.mention")
^^^^^^^^^^^^^
await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
^^^^^^^^^^^^^
Everything is simple here
U already told me
Ok
'Context' object has no attribute 'create_thread'
async def on_message(message):
if(message.channel.id == ID1):
if(message.content != f"Sent verification info. Please check your {ctx.author.mention}"):
await message.delete()
await client.process_commands(message)```
This is the code that deletes everything bessides bot reply to !verify command
And
Hm
Error i get is ctx is not defined
guuyyyyyys I'm here
For ctx.author.mention
Hello guys, I have a question....Can I get a project from the famous bots?
Like a probot
async def on_message(message): > async def on_message(ctx):
message. > ctx.
?
Web?
Do you need a website?
no
ctx.author.mention > message.author.mention
I meant is it possible to take a project from any bot
No
Idk
async def verify(ctx):
await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
await ctx.author.send(embed=main)
await asyncio.sleep(3)
await ctx.channel.purge()
@client.event
async def on_message(ctx):
if(ctx.channel.id == ID1):
if(ctx.content != f"Sent verification info. Please check your {ctx.author.mention}"):
await ctx.delete()
await client.process_commands(message)```
And modify it
do you mean me
I expected that
async def verify(ctx):
await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
await ctx.author.send(embed=main)
await asyncio.sleep(3)
await ctx.channel.purge()
@client.event
async def on_message(ctx):
if(ctx.channel.id == ID1):
if(ctx.content != f"Sent verification info. Please check your {ctx.author.mention}"):
await ctx.delete()
await client.process_commands(ctx)```
Now bot is deleting it's reply
No
Wdym no
await ctx.delete()😭
Read line above that
What do you mean
Okey
Error
Back
async def verify(ctx):
await ctx.send(f"Sent verification info. Please check your {ctx.author.mention}")
await ctx.author.send(embed=main)
await asyncio.sleep(3)
await ctx.channel.purge()
@client.event
async def on_message(ctx):
if(ctx.channel.id == ID1):
if(ctx.content != f"Sent verification info. Please check your {ctx.author.mention}"):
await ctx.message.delete()
await client.process_commands(ctx)```
ctx.message.delete() - Not for you
Wdym
Not for me? For someone else you've said
have you read the docs yet about on_message?
Mhm
it has one param: message, not ctx
Mhm
so if you understand what that means, you should know what to change
Mhm
only a command has ctx as first param, you could add extra arguments, depending if your command needs some
that's all written in the starters guide etc
Thread
'Context' object has no attribute 'create_thread'
class chan1(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
@discord.ui.button(label="", style = discord.ButtonStyle.blurple,custom_id='channel1')
async def c1(self, interaction:discord.Interaction, button: discord.ui.Button):
... #makes a new button with channel.send(view=self, embed=embed)
how would I change label of the newly created button for other than ""
that's correct, you need a channel or message object
right now when I run it, it only produces buttons with "" and I don't know how to change it to something different
There is
async def verify(message):
await message.send(f"Sent verification info. Please check your {message.author.mention}")
await message.author.send(embed=main)
await asyncio.sleep(3)
await message.channel.purge()
@client.event
async def on_message(message):
if(message.channel.id == ID1):
if(message.content != f"Sent verification info. Please check your {message.author.mention}"):
await message.delete()
await client.process_commands(message)```
Why bot deletes it's reply???
you're using a Context object...
you know the difference between a command and an event right?
Mhm
await ctx.create_thread("Text", auto_archive_duration=1440, slowmode_delay=None, reason=None)
Just tell me is there a way for it to not delete it's reply
I guess changing the label of the button...
ctrl+f in chat on how to edit buttons
And it was working well until i added mention
After i added {message.author.mention}
It deletes reply
have you read what I told you?
#discord-bots message
if you just want me to shut up and give you the answer:
await ctx.channel.create_thread(....)
I didn't understand
Can you provide an example?
translator fu*
i can't find it unfortunately
i mean, i know how to edit change it but not for the new button
'TextChannel' object has no attribute 'create_thread'
hmm, on what do you want to create a thread?
Comment below the text
me neither, I'd have to ctrl+F here too
How to do
await ctx.message.create_thread(...)
'Message' object has no attribute 'create_tread'
:/
@client.command()
async def verify(ctx):
await ctx.send(f"Sent verification info. Please check your {message.author.mention}")
await ctx.author.send(embed=main)
await asyncio.sleep(3)
await ctx.channel.purge()
@client.event
async def on_message(message):
# this makes sure the bot doesn't respond to itself
if (message.author == client.user):
return
# this is all bullshit, as the message is already deleted in the verify command
#if(message.channel.id == ID1):
# if(message.content != f"Sent verification info. Please check your {message.author.mention}"):
#await message.delete()
await client.process_commands(message)```
thread
that's what you get for copy pasting
how do i clear all commands of a bot?
just completely remove any and all slash commands?
(this is bc dupes are appearing and they're making me so uncomfortable)
oh ok, but I can't find it like a situation of this, i'll just wait for someone then thx tho
if you just want a quick & easy fix, just regen your bot token
you made a typo
?
I give up, I was clear enough
You are not allowed to use that command here. Please use the #bot-commands channel instead.
you know what I typo is? I'm getting annoyed
try the official dpy support server maybe..
you can find that one on google
okay, thx
isnt it this server tho
no, this is python in general, discord py library has a separate discord support server
it's thread NOT tread
uh...the duped commands are still there lol
that's bad news, uhm. maybe it takes a while (like an hour or so) to desync? not sure
are you auto syncing on startup? that's a bad practice anyways
no
I need to change the nickname of all server members (discord.py)
you know the way choices are in dicts well how would i get all user ids from sql db and make as choice
then loop through each member
and use:
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
#discord-bots message
you're missing the message_content
those are 2 questions
you know how to get all user IDs from your db yet?
yea
Ty i just put all() instead of default() for intents
your db is already connected to your discord bot?
so you can store it in a variable through a command?
that's one way... though you don't really need all
(will result in more RAM usage of your bot)
hi! if someone can help me, why with pycharm its all okay, but with visual studio code give me this error
can I see the line where you pass the token? this can't be the exact same
just remove some letters from the token, idc
yeh, give me a sec
I most likely know what's up, you're getting this token from some file, right?
it has to do with the path
your token isn't properly read, just print it before you put it in the run, you'll see
oh, let me try
yeah, you're having classic pathing issues
I'll fix them for you
so, you've currently hardcoded your path, which means that when you move your project folder, you'll get errors
I'll change the filepath to look for config.json in your current folder ( where your main bot file is too) good?
good
from pathlib import Path
ajam
config_file_path = Path(__file__).parent / 'config.json'
you'll know what to do with that, good luck!
thnak u bro
I need for everyone
async def who(ctx, member: discord.Member, roles=None, author=None):
"""- Displays a users account details."""
if member:
embed = discord.Embed(title=f"User information for {member.name}",
description=f"Join and creation information for {member.mention}")
embed.add_field(name="Server Join:", value=member.joined_at.strftime("%d/%m/%y, %H:%M:%S"))
embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))
embed.set_thumbnail(url=member.avatar_url)
await ctx.send(embed=embed)```
Member objest has no attribute avatar_url
where do you got that attribute from?
?
what's your source? why do you think avatar_url exists?
well, since then, things have changed
I guess so
https://discordpy.readthedocs.io/en/stable/migrating.html#asset-redesign-and-changes ctrl+F on avatar_url
you can scroll through, it's not that big
yup, learning how to use the docs will save you tons of time
So i'm trying to have my bot pin a message that is reacted with 📌
It has a command, and then it has something like
await self.bot.wait_for('reaction_add',check=check,timeout=30)
mhm, the check is important too
make sure it contains the same args as the on_reaction_add would
All of a sudden %M: is invalid syntax
embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))
from now on, just send your WHOLE error traceback with all code you have. you'll get way quicker answers
it's been an hour and the commands are still there lmao
well, I give you an alternative
yeah, i did regen my bot token?
Did you read what I said?
Oh i had links there
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
lol alr
async def who(ctx, member: discord.Member, roles=None, author=None):
"""- Displays a users account details."""
if member:
embed = discord.Embed(title=f"User information for {member.name}",
embed.add_field(name="Server Join:", value=member.joined_at.strftime("%d/%m/%y, %H:%M:%S"))
embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))
embed.set_thumbnail(url=member.avatar)
await ctx.send(embed=embed)```
I don't think you need whole code?
!codeblocks
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
I did it?
I need it in python
@client.command()
async def who(ctx, member: discord.Member, roles=None, author=None):
"""- Displays a users account details."""
if member:
embed = discord.Embed(title=f"User information for {member.name}",
embed.add_field(name="Server Join:", value=member.joined_at.strftime("%d/%m/%y, %H:%M:%S"))
embed.add_field(name="Discord Registration:", value=member.created_at.strftime("%d/%m/%y, %H:%M:%S"))
embed.set_thumbnail(url=member.avatar)
await ctx.send(embed=embed)
url=member.avatar is incorrect
you need a url, you're passing something else, check the attributes of avatar
Okay
also, remember the link I sent you? there's something important regarding the .avatar attribute
hint: #discord-bots message
Discord already have that built-in, why would you create it again
Do people prefer traditional prefix commands or interactions/slash commands?
Prefix commands
more user-friendly is slash commands I'd say
Slash commands are somewhat limited
Because i want 
it tells you what arguments you need etc
noobs don't know how to use text commands
Like member arguments, you can't input IDs there
Would slash commands be better for commands with multiple arguments and prefix commands be better for singular commands?
You can input ints and member objects I think.
just use hybrid commands if you can't pick lol
So should I use both?
you know what a hybrid command is, right?
IDs are too big for Discord to accept
Yes commands that can either be used as a slash command or prefix command.
Try it, or did they fix that?
mhm, so yeah, I'd use both if you can't pick
I’m pretty sure it’s been fixed
A integer parameter.
I don't know about you, but I wouldn't add a new argument just for IDs
Idk you can just ask for the person to mention someone in a slash command
Some time the server is big
And usernames are not limited to only English letters
You can easily miss the target member
which means you wouldn't be able to mention them?
I'd just copy paste their name, no escaping that
uh i just synced my discord commands (they're all hybrid_command or commands.command)
but the slash commands aren't registering?
prefix commands work (a.inventory) but slash commands don't & give this error: https://paste.pythondiscord.com/ekomezifus
I think slash commands need a response
I would use something like member context manager and get inputs from a modal instead
yeah, the command i'm testing gives an embed as the response
hm
How are you defining your commands and how are you syncing?
I think you synced to the wrong scope before and now they don't exist in your code but they do on discord
This has nothing to do with responses
method header here: https://paste.pythondiscord.com/wobopiriza
sync command here: https://paste.pythondiscord.com/eteqedivix
@client.event
async def on_message(message):
if message.content == "Help":
await message.reply("**If you're asking for help just watch fucking tutorial [#1061090311314624522](/guild/267624335836053506/channel/1061090311314624522/) watch it from top and then if you still don't understand something just dm @fervent escarp**")
What's wrong i get no errors but bot won't respond
Do you have the message_content intent?
I made 4 same events just another message like help, Help, how to
I have all
intents = discord.Intents.all()
client = commands.Bot(command_prefix = "!", intents=intents)
client.remove_command('help')
What? How are you making those
how could this even happen?
I'm not sure sorry, you could try syncing an empty tree to clear it then sync the hybrid commands
yeah that's what i did
oh wait hold on lemme try something
lmao
now the commands aren't show up at all
here's my command history along with the code i have for sync & unsync: https://paste.pythondiscord.com/biwimuluta
bruh i just got ratelimited
sucks, spoof your mac , ip , clientsession, account
that sounds sus, and might violate rule 5 of this server
rate lim
make your sync command have an option menu btw, so you don't have to care about wrong scope values
idem for unsync
but sync commands are prefix commands?
ah, in that case, maybe make a custom typehint, ~enum
SYNCSCOPE.GUILD
or SYNCSCOPE.GLOBAL yk
idk what the pep (~correct casing) is for enums tho, so this uppercase might not be needed 🙂
No documentation found for the requested symbol.
https://docs.python.org/3/library/enum.html
the official docs use all caps, so i guess that's the correct convention
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#ext-commands-flag-converter This should be available in v2.0
I think it would be cool to make your sync command using flags, it's versatile
the class itself isn't, so I guess SyncScopeEnum.GUILD & SyncScopeEnum.GLOBAL
oh lol
is this okay? what i wanna do is, when someone click the button, it first get the person who clicked and then add it to a mysql database
why?
Why what
this xd
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
ohhh
aiosqlite is asynchronous binding for sqlite3, so it's not blocking but still is the same
!pypi aiosqlite
thank u bro
can someone tell me why the default value for inline in Embed.add_field is true
because the majority of the time i want it to be false
in most cases, users want the fields to be displayed inline with each other. This allows for a more compact and visually appealing layout, as the fields will be displayed next to each other rather than stacked on top of each other.
well i guess i'm in the minority lmao
lmao right
depends on the specific use case and what the user finds to be more visually appealing and easy to read.
so rn my cogs are like this:
i'm concerned about the # of cogs getting out of hand later on
can i organize them into subdirectories & still have them all load?
Ye
Sure, but there shouldn't really be an issue with a lot of cogs in your cogs folder (I mean, that's the point, isn't it?)
You can create a package for each cog. setup would be in subdirectory.__init__, and you could have the actual cog in a file called subdirectory.cog or whatnot. Then you can use the pkgutil stdlib module to load all of them automatically
Our bots like @unkempt canyon have a crap load of cogs
yeah, but those cogs are organized into separate directories
subdirectory.cog
shouldn't all python files be.pyfiles?
nah
file extensions are pretty much worthless
ok but
my ide cares
File extensions actually pretty much mean nothing, and are just an indicator to your OS connecting it directly to a program
alr then
Then you can use the pkgutil stdlib module to load all of them automatically
is there a tutorial/example for how to do this?
@client.listen()
async def on_message(message):
if message.author.bot:
return
For some reason when I have that if message.author.bot it sends things twice, but when i remove it it works, howeverrr i also dont want the bot to trigger the other stuff in my on_message, any ideas?
Do you have another on_message anywhere?
no o:
Can you show us your rank command?
@client.command()
async def rank(ctx):
args = {
'bg_image': rank_card_backgrounds[config[str(ctx.author.id)]["rankcard"]-1],
'profile_image': ctx.author.avatar_url,
'level': xp[str(ctx.author.id)]["level"],
'current_xp': 0,
'user_xp': xp[str(ctx.author.id)]["xp"], # User current xp
'next_xp': level_thresholds[xp[str(ctx.author.id)]["level"]],
'user_position': lookup.get_leaderboard_position(str(ctx.author.id), xp),
'user_name': ctx.author.name,
}
image = Generator().generate_profile(**args)
file = discord.File(fp=image, filename='image.png')
await ctx.send(file=file)
However its not just the rank command, its any command i send
Can you show us your entire on_message?
@client.listen()
async def on_message(message):
if message.author.bot:
return
user_id = str(message.author.id)
if user_id not in config:
config[user_id] = {"level_up_message_active": True, "rankcard": 1}
user_config = config[user_id]
if user_id not in xp:
xp[user_id] = {"level": 1, "xp": 0, "cooldown": 0}
user_xp = xp[user_id]
if user_xp["cooldown"] <= 0:
user_xp["xp"] += random.randint(1, 3)
user_xp["cooldown"] = 15
while user_xp["xp"] >= level_thresholds[user_xp["level"]]:
user_xp["xp"] = user_xp["xp"] - level_thresholds[user_xp["level"]]
user_xp["level"] += 1
if user_config["level_up_message_active"] and message.channel.id not in blacklist:
await message.channel.send(f"{message.author.mention} level up to {user_xp['level']}!")
for i, rank in enumerate(rank_thresholds):
if user_xp["level"] >= rank["threshold_level"]:
role = discord.utils.get(message.guild.roles, name=rank["name"])
await message.author.add_roles(role)
await saves.save_xp(xp)
await saves.save_config(config)
hmmmm
I'd check to see if you have another bot process running
If you're not sure restart your computer
will check gimme a moment and ill let ya know
huh yeah idk why that was happening then, never had that issue
Did restarting fix it?
yeah
Well you know what they say
"Have you tried turning it off and on again?"
Question: How do I loop voice_client.play() when it ends? I tried to look on discord.py docs but could be missing something.
!d asyncio.run_coroutine_threadsafe
asyncio.run_coroutine_threadsafe(coro, loop)```
Submit a coroutine to the given event loop. Thread-safe.
Return a [`concurrent.futures.Future`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future "concurrent.futures.Future") to wait for the result from another OS thread.
This function is meant to be called from a different OS thread than the one where the event loop is running. Example...
#message delete
@commands.Cog.listener()
async def on_message_delete(self, message):
async for entry in message.guild.audit_logs(action=nextcord.AuditLogAction.message_delete,limit=1):
embed=nextcord.Embed(title="Message delete", description= f"Deleted by {entry.user.mention} \(this is unreliable\) in {message.channel.mention}\nMessage: {message.content}\nMessage author: {message.author.mention}",color=0xfd9fa1, timestamp=datetime.datetime.utcnow())
does anyone know what i should put in place of entry.user.mention so that it correctly mentions whoever deleted the message?
i dont think that shows who deleted the message, just that someone other than the author of the message deleted it
at least according to the docs it doesn't say it does
its also not very reliable to use audit log to track actions, doesn't always get added
ah, so theres no way to do it
hi, i want change my main page with TOken line by a .env file with token,
After import os and dotend (load_dotenv) i have a issue:
TypeError: expected token to be a str, received NoneType instead
iit already installed
install it and add ```py
import dotenv
dotenv.load_dotenv()
import discord
from discord.ext import commands
from cogcmd.cog_info import cog_info
from cogcmd.cog_cmd import liste_commandes
import os
from dotenv import load_dotenv
intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", intents=intents)
load_dotenv()
TOKEN = os.getenv("TOKEN")
@bot.event
async def on_ready():
print("Le bot connecté")
await bot.load_extension("cogcmd.cog_info")
await bot.load_extension("cogcmd.cog_cmd")
bot.run(TOKEN)
what is the error? 😕
Do you have a TOKEN key set in your .env file?
yes
well the error means that you dont
in .env file:
TOKEN = MTA2MzU0MzAw
print os.environ to make sure it is or not
what do you mean?
@slate swan
this is my problem, thats good now
it because i dont save my file before run the command
now i can share my source code ^^
~~i am using pycord and in one of the cogs, i want to use bridge_command so i used ~~
@commands.bridge_command(guild_ids = ids, name = "snipe", description = "Gets a deleted message")
just as in discord.py commands.hybrid_command()
~~but i get this error - ~~
AttributeError: module 'discord.ext.commands' has no attribute 'bridge_command'. Did you mean: 'message_command'?
so how should i use bridge cmds in cogs?
Got it...
Guys can you help me
How to connect python vscode with powershell
It's opening Microsoft Store if I type python in powershell
anyone know how to fix this? im pretty new to coding and i just used a sample code from a video and altered it a bit (repl.it)
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
hm
Hold on, why is it that when I do this, only some people can do it
hd not in interaction.user.roles doesn't work on some people for some reason
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
Smort
Amort
its an actual word
how do i get the object role of the role using just the id?
the <> format
What
The when the what the you is mean?
Role mention or smth
nvm
also how do I limit a button to only one person being able to click it once
i tried button disable but if in time, 2 people can still click in same time
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
Override this in your subclass
wdym
Simple OOP
ok
so where should i put this
me no like such questions
Typically person who asks like this doesn't even have OOP knowledge
ok
Anyways you got the subclass of discord.ui.View right?
yes i do
Hold up a bit I will explain that