#discord-bots
1 messages · Page 868 of 1
whelp dont turn your bot off
i can't be sidetracked
it's pronounced thirtween

o
you used double =
ahhhhh
prolly should learn more Python before getting deeper into the bot
whats wrong with f strings
Jonathan doesn't use them
@commands.slash_command()
async def botinfo(self, inter):
infoEmbed = disnake.Embed(
title = "Heya!",
description = "This is a description."
.add_field(
name = "Hey!",
value = "Please work..."
)
)
await inter.response.send_message(embed=infoEmbed)
I get an error with this when the command is run
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'add_field'
Any idea why?
"This is a description is a string"
'str' object has no attribute 'add_field'
place add_field outside of the embed constructor
outside of the brackets
It works now! Thanks!
Variable names should be in snake_case, not camelCase
[WinError 2] The file can not be found.```
Any1 know this problem?
Nope.
Yes
Calling it bot_info makes it break, as in it doesn't load it
Never said anything about function names
[WinError 2] The file can not be found.```
Any1 know this problem?
I need som help
Stop spamming
Okay sorry...
Sorry, haven't slept in a day or two, I see what you're on about, why should it be snake and not camel?
Pythons style guide (PEP8) has it listed that variable names should be in snake_case. It's also listed that camelCase should never be used in python
pep8 isnt mandatory
Never said it is, it's just highly recommended
It's incredibly useful
ok
it wouldn’t exist if they didn’t think it was necessary
How do I use a custom emoji in an embed from a specific server?
<:emojiname:emoji_id>
How do I get the id?
right click on the emoji
it also wouldnt exist if it was meant to be mandatory
Wut
Think about what you just said
this makes me want to die
I can't, I'm on mobile
...
idk then
i did 🤣 its not meant to be mandatory
i dont use mobile
hello, i have a new problem that appears and i don't know how to fix it, this is my code : ```python
@tasks.loop(seconds = 5)
async def changeStatus():
game = discord.Game(random.choice(status))
await bot.change_presence(activity = game)
status = ["+help | Dr Maboule#4456", "Hello world"]
I never said it was mandatory
ok
you defined status after you used it
Function names should be in snake_case, not camelCase
put status before game
also its outside the function
ok its really strange is was never problem with this before
you are trying to use the list before it even exists i think it would probably be an issue
any1 help me?
Dont ask for help just say it
okay
await msg.channel.send(file = discord.File(fp=payment.mp4))
[WinError 2] The file can not be found.
Code?
@tasks.loop(seconds = 5)
async def changeStatus():
status = ["+help | Dr Maboule#4456", "Hello world"]
game = discord.Game(random.choice(status))
await bot.change_presence(activity = game)
``` like this ?
is this file in the directory?
i dont have the file i got it from a friend
and it works for him
and he does not have it aswell but it works to launch it for him
br
what? "br"
@left crater thats dont work
Try asking in #databases
indent it
async def changeStatus():
status = ["+help | Dr Maboule#4456", "Hello world"]
game = discord.Game(random.choice(status))
await bot.change_presence(activity = game)```
yes thats don't work i have the same problem
error?
the same, :
!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.
https://paste.pythondiscord.com/vimewadiki ``` File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\llVll\Desktop\TMG Bot\main.py", line 16, in on_ready
bot.load_extension("cogs.maincommands")
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\llVll\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.maincommands' raised an error: AttributeError: module 'discord.ext.commands' has no attribute 'event'
you dont do @commands.event, you do @commands.Cog.listener
also you need self, message and self, ctx
classes take self as their first arg
line 212 be wildin
jeez ive seen everyone copy and paste that crap tictactoe command
its not even good, it uses global
someone now why bot don"t want to reply when a command is a embed ?
you gotta send the embed
embed=embed
await ctx.send(embed=embed)
after u built ur embed
i now
is there an error code?
no one its appears right know
what appears
this "bug"
@bot.command()
async def disquette(ctx):
embed = discord.Embed(title = "✉️ **Disquette**", description = f"{ctx.author.mention} {random.choice(disquettes)}", color = 0x9400D3)
await ctx.send(embed = embed)
@bot.command()
async def blague(ctx):
embed = discord.Embed(title = "🤣 **Blague**", description = f"{ctx.author.mention} {random.choice(blagues)}", color = 0x9400D3)
await ctx.send(embed = embed)
@bot.command()
async def meme(ctx):
await ctx.send(f"> {ctx.author.mention} : Clique sur le lien pour télécharger la vidéo ! {random.choice(memes)}")
@bot.command()
async def nombrerandom(ctx):
nombre = random.randint(0, 1000)
embed = discord.Embed(title = "1️⃣ **Nombre**", description = f"{ctx.author.mention} {nombre} !", color = 0x9400D3)
await ctx.send(embed = embed)
@bot.command()
async def pileouface(ctx):
embed = discord.Embed(title = "❔ **Pile ou face**", description = f"{ctx.author.mention} {random.choice(pileouface)} !", color = 0x9400D3)
await ctx.send(embed = embed) ``` @scarlet aurora maybe because the {random.choice(-----)} is on the end of my code ?
yes its
what are you trying to do when you assignment empty a value?
because empty is a list, and lists have no attr array
thats for the later code
are you trying to set empty to empty = []
just do if len(message.attachments) == 0:
what is len?
length of items in an array
Hey joe cena any chance you can help me with my bot here once you’re done helping jonathan55?
mine had a minor bug
so, the command is supposed to push a nickname onto a member?
Yeah and it wouldn’t let them change it until they leave voice chat
noq
I’ve got everything working, but it won’t force it on them
what do you mean?
like if I type hi in the bot DM
what did you expect to happen if you type hi
@tasks.loop(seconds = 5)
async def changeStatus():
game = discord.Game(random.choice(status))
await bot.change_presence(activity = game)
``` hello, i have this error with this code :
are you getting an error?
no
it just wont send the message I sent to it in the modmail channel
instead of using await modmail_channel use await message.author.send
cause that is in the ( )
do await message.author.send(f'[{message.author.display_name}]')
did you create a command like @bot.command() async def random(ctx): by any chance?
yes
alr then
thx man
@quaint epoch its broken some more
do py @tasks.loop(seconds = 5) async def changeStatus(): import random game = discord.Game(random.choice(status)) await bot.change_presence(activity = game)
alr send code
did you get an error?
so what output did you get?
Hey @quaint epoch sorry for bugging you again but I could also really use some help
I’ve been trying to force the nicks for atleast an hour now
alr lemme try and fix your code
@bot.command()
async def nick(ctx, channelid, nickname):
if str(ctx.author.id) != "422025717602320385":
return
channel = await bot.fetch_channel(int(channelid))
for member in channel.members:
await member.edit(nick=nickname)```
if it doesn't work change await member.edit(nick=nickname) to await member.edit(nickname=nickname)
The problem when I do this is that it won’t change anyones nicknames because I am in the voice chat
I get missing permissions as an output and it doesn’t change anyones
I tried adding a try and except because of that
what perms did you give your bot?
It has admin too
But I am an admin too
then it can't change your nickname, because you have higher roles/perms
The code I have right now changes everyones nicknames except for admins
Because it has try and except
But it won’t force it on the members
I just need it to repeat the action
so it’s forced
async def nick(ctx, channelid, nickname):
if str(ctx.author.id) != "422025717602320385":
return
channel = await bot.fetch_channel(int(channelid))
userids = []
users = channel.members
for member in channel.members:
print(member)
if member.display_name != (nick):
try:
await member.edit(nick=nickname)
except:
continue```
Thank you
did it work?
so Continue makes it go back to if member.display_name?
Haven’t tried, one minute
well i'll be having tutions soon so i may not be able to respond
Nope its the same again
It changes everyones except mines nicknames once, but it doesn’t force it
It’s probably going to work if I put something below “except:” that returns to “if member.display_name”, but I can’t figure out how to do that
Don't do a bare except
bare = nothing under it?
You're spoonfeeding bad code lmao
No,
# Bare exception (bad)
try:
raise ValueError
except:
pass
# Catching the specific error (good)
try:
raise ValueError
except ValueError:
pass
What do you suggest I put after except?
Check what error it throws and catch it
It doesn't throw any error, it just partially does what I want it to do
There is no error
I have no idea what you're doing. Can you give me a recap?
@bot.command()
async def nick(ctx, channelid, nickname):
if str(ctx.author.id) != "422025717602320385":
return
channel = await bot.fetch_channel(int(channelid))
userids = []
users = channel.members
for member in channel.members:
print(member)
if member.display_name != (nick):
try:
await member.edit(nick=nickname)
except (discord.Forbidden, discord.HTTPException):
continue```
would this work
you'd have to remove perms for them to change their nicks
...They have no perms
You mean disable change nicknames on @/everyone
yes
I don't want that though
Users should be able to change nicknames when they aren't connected
Hello everyone !
then everytime a user a joins you'd have to change perms
Can I just not have "except:" go back to "if member.display_name != (nick):" though?
Thats what I'm aiming for
you'd have to check what error is raised and except that
There is no error though
give your bot higher perms than everyone
Dude
why convert and int to a str just to compare the int just compare it as is?
The bot is working completely fine I just want it to keep changing the nicknames
Right now its doing it only once
- Where are the type hints
- Why are you casting the author's id to a string, just compare the integer values?
useridsisn't usedusersisn't used- Why are there
()aroundnick(nickisn't even defined) continueis only used in loops- Use a decorator to check if you're the owner
I have author id so that only I can use the command
Just use a decorator
✌️ Hi !!
I need couple suggestions, if you guys can help me. I'm new to coding discord bot, I used multiple prog. languages in the past but now I wanna try Python to make funny Discord bots and rogue-like/labyrinth text-based mini-game for Discord.
I would like to know what should I use as discord.py seems discontinued. I'm trying Hikari+Lightbulb, but lot of people refer to others well-known. Just asking for opinions here. I would like to use !command or /command, and react to arrows in order to move in the labyrinth (all text-based + roll dice and events).
Can someone tell me how I can make except: go back to somewhere else in the code
!d discord.ext.commands.is_owner
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Did not work
Show how you did it...?
I don't see why I should change it the one I have right now does literally the same thing
Can you please tell me how I can make it so that except: goes back to another part of the code
Readability + what you have now is werid
Do you know how I can make except: go back to another part of the code?
what are task loops used for normally ?
sending stuff to channels on an hourly basis, all sorts of jazz
Really not just 1 purpose
what would be a good approach to check for new yt uploads / twitch stream on ?
crontab
I would think a task but there might be a better solution
I've been asking about 1 simple thing that I dont know how to do for 30 minutes and I've gotten literally 0 help
rip
Then wait longer
ask smarter people
Caeden do you know how I can make it so that once it reaches a part of the code it goes back above to another part?
#python-discussion , you make functions
alr
you cant just simulate a cursor hop, but you can create functions with your code in them and call it multiple times
If you honestly think you help people then I’m sorry but you’re just wrong, literally all you’ve done was calling my code bad and telling me to wait longer
😳
Never called your code bad, called the other persons code bad
And it was
That was literally mine but ok
Here are some suggestions to improve it
so I'm trying to start using cogs. But I'm having issues with the event on_command_error
@commands.Cog.listener()
async def on_command_error(ctx,error, cog):
if isinstance(error,commands.MissingPermissions):
await ctx.reply("You do not have the required permissions to execute this command.")
elif isinstance(error,commands.MissingRequiredArgument):
await ctx.reply("You are missing some arguments.")
elif isinstance(error,commands.errors.MissingAnyRole):
await ctx.reply("You are missing the required role to execute this command.")
elif isinstance(error,commands.errors.MemberNotFound):
await ctx.reply("Error: Member Not Found")
else:
raise error
thats what I have.
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/runner/captain-test-bot/venv/lib/python3.8/site-packages/discord/client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "/home/runner/captain-test-bot/cogs/events.py", line 39, in on_command_error
raise error
TypeError: exceptions must derive from BaseException
thats the errror.
I have looked on google, but I'm still confused
well
because its inside a class you pass self, ctx, error
and on_command_error doesnt take cog
even without cog as a argument, i get the same error
i get same error with those arguments
no, it will be fine if you do self, ctx, error
i get same error with those arguments
show your code
import os
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
import time as tm
import discord.ui
from discord.utils import get
import discord
from discord import Intents
from webserver import keep_alive
import functions as f
from replit import db
import requests as rq, json
PREFIX = "-"
class events(commands.Cog):
def __init__(self, client):
self.client = client
#Events
@commands.Cog.listener()
async def on_ready(self):
activity = discord.Game(name=f"{PREFIX}help", type=3)
await self.client.change_presence(status=discord.Status.online, activity=activity)
print('We have logged in')
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error,commands.MissingPermissions):
await ctx.reply("You do not have the required permissions to execute this command.")
elif isinstance(error,commands.MissingRequiredArgument):
await ctx.reply("You are missing some arguments.")
elif isinstance(error,commands.errors.MissingAnyRole):
await ctx.reply("You are missing the required role to execute this command.")
elif isinstance(error,commands.errors.MemberNotFound):
await ctx.reply("Error: Member Not Found")
else:
raise error
def setup(client):
client.add_cog(events(client))
^^^
are you sure youre saving it and rerunning your bot? try printing ctx and errr
im not a fan of those unused imports either
Class names should be in PascalCase
whats that?
What do you mean?
what is PascalCase
cibere did you fix your problem?
nope
How class names should be named
what happened when you printed ctx and error?
can i see an example?
Of just PascalCase?
class ThisIsAVeryLongClassNameWrittenInPascalCase:
...
uhhh it somehow started to work once i put the print statments in
oh camelCase
huh?
you mean it suddenly started working when you saved and reran the code? …
no, i mean it litterly just suddenly started working.
my code auto-saves when i run it
adding print statements doesnt fix code. all you did was save and rerun it.
either way, it works 🙂
camelCase is definitely not PascalCase
Also, camelCase should never be used in python
So tbh I don't know what you're talking about
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
All of the examples of camelCase I see are written as camelCase, not CamelCase
please go to an off topic channel
thats not camel case lol
Yes it is
camelCase PascalCase
wut
I know the difference between camelCase and PascalCase
then what are you talking about lol
Reptile said camelCase is written like CamelCase
CamelCase is not camelCase
That's PascalCase
There are some variations of camelCase written like that but the original camelCase is definitely not CamelCase
In PEP8 they reference camel case as CamelCase
As I said above I think it's because of all the variations of it
ig its both loll
🗿
so, my status is Why do I hafe tp fix typos?, how does my bot detect it AND my bio?
better worded, how find member status and bio
Does anyone know the best website/application to host and code (python) a discord bot on, ( so that no one else can access the code and is online 24/7)
Code in a code editor/IDE and host on a VPS
👍
Can I host on Raspberry PI?
8GB
or would it be easier to just host on a vps
yes
but the size of your bot changes what raspberry pi to host on
I would just do a VPS
Ok!
The bio cannot be seen be bots
im back with a question
how i can put my bots status o online ?
Is this the channel to ask for help with discord related bots CODE?
run the bot
Oh wait
ok so I made a activity command for my modmail bot but it wont go through, no console errers, and this command works on my other bots
without any codes ?_? how does that work
Also, is it possible to have more than one Webhook link on replit? to send messages?
you make code to run the bot
and the bot is online when it’s run with the correct token
alr im confused but thanks
@quaint epoch if you could help it would be great!
you probably shouldn’t name your variable client if you are instantiating Bot
Send the entire file and don't name your commands.Bot instance client
!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.
makes sense
nah that crashed
Yeah you need to refactor every client to bot
?help
youtube tutorial?
idk
@final iron no that didnt work
hmm i refactored all the client to bot
but that didnt work
Im getting a TypeError: 'set' object is not callable. How would I fix?
import discord
from discord.ext import commands, tasks
import os
from keep_alive import keep_alive
client = commands.Bot(command_prefix="-",
help_command=None)
name = "astolfo"
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.commands()
async def ban(ctx, user, reason):
await ban(user=user, reason=reason, delete_message_days=7)
from discord.ext import commands, tasks
import os
from keep_alive import keep_alive
client = commands.Bot(command_prefix="-",
help_command=None)
name = "astolfo"
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.commands()
async def ban(ctx, user : discord.Member, reason=None):
await ban(user=user, reason=reason, delete_message_days=7)```
I still get it
Don't spoonfeed
i just took his code and changed one thing\
Please read this tutorial
https://vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
I can see so many things that are wrong
say user.ban(reason=reason)
Wont work
why
Wait you type hinted user to a Member object
If you're going to spoonfeed at least don't give bad code
And you could of at least changed it?
tbh you shouldn't spoonfeed if you don't know what you're doing
he can name things whatever he wants to name
technically they can but it's terrible practice
then he can change it
Either way please don't spoon feed, we're a community that helps people through their problems in Python, not one where people can say "heres code, heres error, fix please"
But you spoonfed them without explaining so I doubt they know why it's bad and how to change it
i guess
I'm assuming they already copy pasted it and moved on
Which is unfortunate because now they have bad naming practices
Also why use .format when you can use f-strings
No actually I looked at it with confusion then tried it then it ended up not even working
thats not me
The person who coded it was using old code iirc
That seems very familiar, youtube tutorial?
Yeah
Yeah I would suggest you stop watching that
most of them are usually outdated
They also follow some really bad practices
I've seen one too many use json as a database and it drives me insane
I stopped watching them and stuck to docs + other resources
that's awesome
However, the bases of this bot were based on yt
Try reading this tutorial over
I think that's alright as long as you're actively fixing and improving it
Hi, so am I just not able to use f-strings in a Disnake embed?
@commands.slash_command()
async def botinfo(self, inter):
infoEmbed = disnake.Embed(
title = "bot.user",
colour = disnake.Colour(0x1abc9c)
).add_field(
name = "Bot Stats:",
value = f"ID: {bot.id}
\nName: {bot.user}
\nHighest Role: {bot.highest_role}"
)
await inter.response.send_message(embed=infoEmbed)
value = f"ID: {bot.id}
^
SyntaxError: unterminated string literal (detected at line 17)
That pointing at the f btw not the :
variable names should be written in snake_case, not camelCase
Will that help me with the error I have?
They all need to be on the same line unfortunately
You've said. I prefer camelcase.
If you want them to be seperated into multiple lines consider using triple quotes
Using camelCase is wrong 🤷♂️
youre wrong
I'll try that and see what happens
Possibly
Nope, give pep8 a read over
you don't want to argue with @final iron over pep8, trust me
I have, but like idc much for pep8.
It's optional in my eyes.
With the exception of the indents
Alright, Ill look it over. Thank you
The indents are not part of pep8, it's a fundamental part of the language
Your problem could be technically considered as an indentation problem
hey my bot just got over 6.5k servers and i want to implement sharding but autosharding is incredibly slow and it takes my bot ages to load up
No liek the indents being 4 spaces or something
can someone help me with making a certain amount of shards
Damn, that's a lot of servers
Spaces over tabs
it was in more but people are kicking it cuz i cant figure out the issue
I tried triple quotes, it stopped bugging me about the string literal, then it started saying that bot isn't defined when I run the command.
import disnake
from disnake.ext import commands
class UltimatumInfo(commands.Cog):
"""Displays the info for the discord bot."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.slash_command()
async def botinfo(self, inter):
infoEmbed = disnake.Embed(
title = "bot.user",
colour = disnake.Colour(0x1abc9c)
).add_field(
name = "Bot Stats:",
value = f"""ID: {bot.id}
\nName: {bot.user}
\nHighest Role: {bot.highest_role}"""
)
await inter.response.send_message(embed=infoEmbed)
def setup(bot):
bot.add_cog(UltimatumInfo(bot))
print(" | Loaded Extension: Bot Info")
print(" | ")
Spaces over tabs doesn't matter in an ide as it usually just inserts 4 spaces if you press tab
Just wondering but what happens if you don't shard your bot?
self.bot not bot
it doesnt start
cuz once u get 2.5k servers u need to shard
Oh
Apparently Bot object has no attribute id
Are you doing self.bot.user.id?
i- no, that would make sense
I didn't include user lmao
How do I get the bots highest role?
In Disnake
ctx.me returns a discord.Member object for the bot when used in a guild
You can then get the roles of the discord.Member object with
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
Take note of this: These roles are sorted by their position in the role hierarchy.
If you want to read more about ctx.me I'll send the docs
Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.
.
So Player1041#3716? Sorry if I sound dumb as fuck
Haven't slept in 2 and a bit days
You know what a discord.Member object is, right?
You can use all the attributes on it
Like id, name, joined_at
All that jaaz
Then you have methods like ban() and kick()
tbh anything
Just make sure I know you're talking about me
So ig water_gazes is fine
You can also just call me water or gazes
Ok, thanks water :)
This instantly fails, why?
@commands.slash_command()
async def botinfo(self, inter):
me = ctx.me
infoEmbed = disnake.Embed(
title = "bot.user",
colour = disnake.Colour(0x1abc9c)
).add_field(
name = "Bot Stats:",
value = f"""ID: {me.id}
\nName: {me.user}
\nHighest Role: {me.top_role}"""
)
await inter.response.send_message(embed=infoEmbed)
I'd assume from changing all the bot to me as in me = ctx.me
So it should be returning the disnake.Member shit
But it ain't and I imagine it's something to do with ctx
property user: Optional[discord.user.ClientUser]```
Represents the connected client. `None` if not logged in.
ClientUser is essentially a discord.User object with a bit more attributes
Actually nvm
Because you're getting the roles
So you need a member object
Give me a second
me.user, Member object doesn't have user attribute
User object doesn't have a top_role attribute either
It does in Disnake.
No it doesn't
!d disnake.User
class disnake.User```
Represents a Discord user.
x == y Checks if two users are equal.
x != y Checks if two users are not equal.
hash(x) Return the user’s hash.
str(x) Returns the user’s name with discriminator.
Wait that's member- wait that's what I'm using with ctx, it returns disnake.Member
Mhm, and you said:
ctx.mereturns adiscord.Memberobject for the bot when used in a guild
Yeah but you don't have access to ctx
You're in a slash command
How do I get access to ctx then?
ah didn't saw that
Union[Member, ClientUser]: Similar to Guild.me except it may return the ClientUser in private message contexts.
There ya go
So it would be inter.me
inter.me will return your disnake.Member object for the bot
Nice
Final thing, how do I make it ping the highest role? The colour looks nice lmao
!d discord.Role.mention
property mention: str```
Returns a string that allows you to mention a role.
lol
which fork of discord.py is recommended? disnake or pycord?
d i s n a k e
I'm using Disnake atm and it's working pretty well from what I'm seeing
disnake. pycord is the least recommended fork
Pycord is shit

@graceful oyster
Can't in a slash command
Isn't it like Hikari (if you're feeling adventurous), Disnake, Nextcord, everything else, pycord?
rin should be first smh
what's rin?
!pypi rin
It's made by our very own andy
who is andy
270700034985558017
He's in #ot2-never-nester’s-nightmare right now
oh
1-10, rate
🗿 lol ok
\nHighest Role: {disnake.Role.mention(me.top_role)}
That says it's not callable. I just want to mention the top role lmao
'property' object is not callable
Ohhhh
Discord.py has tons of object oriented programming
So me.top_role(mention)?
Hey, does anyone know how i let my discord bot write a message when someone get the status "online"? Im a beginner in python. I try it multiple times but i dont get an error or something.
So you want it to send a message each time someone comes online?
Yes
tf
I tryed it with on_member_update
I'm tired ok :(
it is top_role.mention
Ah, ok
how do i check if a user is premium?
Thanks Kai
like subscribed to nitro
Shit, one sec
!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.
This is just if used their “Nitro boost” on the guild
okay so how about nitro itself?
You can't "check" if someone has nitro, bot's can't do that.
darn
Privacy thing.
Makes sense why it's a privacy thing but the api people could just make a simple check for if the user in question has nitro on the account using boolean or some shit idk
You can't with bot's you could with user token but that is against ToS
Yeah..
How do I get the UNIX Timestamp for when a user or a bot joined the server?
That and also their accounts creation date
Else I get this monstrosity of a timestamp using joined_at
I got that bit working
member.joined_at.timestamp()
It's me.top_role.mention
Yeah that's your unix timestamp
You wanna use discord timestamp formatting to make it look sexy?
Shit, I meant like this lmao
Yup
Yes, yes exactly that, I want to format it to make it look readable
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Here are your options for the styles
Tell me which one you want
So you would do
<t:123123123:D>
<t:123123123:D>
123123123 is your unix timestamp
tbh I might just spoonfeed you this as it's quite hard to explain and a lot of people don't get it
<t:1646095684:R> :3
I think I got it, ima test it rq
Nope, didn't get it
I made an attempt at least lmao
You need to remove the decimals
You can use round() to do that
!e
print(round(123123.834))
@final iron :white_check_mark: Your eval job has completed with return code 0.
123124
<t:20182747:D>
You also can't have timestamps inside of embeds.
Believe me i tried.
You can't?
Hey, does anyone know how i let my discord bot send a message when someone comes online? Im a beginner in python. I try it multiple times but it doesnt work and i dont get an error or something. I used the bot event async def on_member_update but all my trys to get the status doesnt work.
Oh yeah?
Nope, same as you can't mention anything in an embed.
Did they update that :3
Yeah I was 100% you could use timestamps inside of embeds
🤷♂️
If my eyes aren't decieving me, it seems almost like it's a timestamp and a mention inside an embed
Ohh no you can't have timestamps inside the embed footer
That was annoying
Yeah creb
Ah, yeah I can see where that's annoying
The timestamp format inside the footer was an ingenious idea pre-ruined by Discord
For my footers, I'm just slapping my name and if possible a small McDonald's gecko (my pfp) in the corner with it
Yk, be simple with it. No need for a timestamp when there's a perfectly fine time and date next to the users name
Yeah but with the time format it says how many hours, days, or months ago now i need to use my brain
Fair enough
Theres a timestamp kwarg in the embed constructor
there's a what in the where now
timestamp kwarg
!d discord.Embed
class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
What does it do docs explain 0 shite
Timestamps probs
It's like a less fancy timestamp
(╯°□°)╯︵ ┻━┻
Is there not a way to make the timestamps work in the footer?
If you can dm me
What?
If you can get the timestamp to work inside the footer, what we were talking about. Inside the Embed, then please direct message or ping me and tell me what you did. Thanks for reading.
you can use utcnow in footers
We're not talking about alternatives here.
Not the <t:132132123:D> timestamp
I'm gonna try and get it to work lnao
How do I make a footer 🧍♂️
🤦♂️
set_footer(*, text=Embed.Empty, icon_url=Embed.Empty)```
Sets the footer for the embed content.
This function returns the class instance to allow for fluent-style chaining.
where do you instantiate the bot
instantiate??
pass_context is also legacy
He means initialize.
ohh
That's called defining a class.
you define a class like so:
class SomeClass:
...
ahh there,
You instantiate/initialise a class by doing SomeClass()
It's making an instance of the Bot class
@client.command in your case. But you shouldn’t name it client if you are making an instance of commands.Bot
Now you would just be calling it.
You don't really "call" a class in the way you do a function
I guess you could say you "call" the __init__
__call__ is going to participate in this conversation.
I suppose but I think instantiation/initialisation makes more sense for terminology
No the init get initialized.
__init__ got called in __new__
only if it returned a class
Converting all class methods to functions just to confuse the people who steal my code.
Dot?
They're bumping the message
Isn't there a has_permissions() check or am i crazy
!d discord.ext.commands.has_permissions
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
It exists
I can still see it
thanks
you can handle that in on_command_error with MissingRequiredPermissions or with a try except block in the command body
!d discord.ext.commands.Bot.on_command_error
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
at least i'm not crazy 😄
fast and easy question how do i make it so after a person executes a command the message get's deleted
i forgot btw ^
thanks man it worked
and you would need the @has_permissions() decorator to specify who can even execute the command without errors in the first place
ctx.message.delete() deletes the authors message.
Which message? The one they sent of the one the bot sent
👍
the one i send to execute the cmd
quick question again how do i make it so when i startup bot it prints something
@bot.event
async def on_ready():
print("Ready!")
ty
how would i make it so after a certain amount of time my button get's disabled using discord.py
…i recommend learning python before making a bot!
what command use to get user avatar?
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.avatar "discord.User.avatar")
ty
This returns an asset object
Which you would use the url attribute on to get the avatar url
!d discord.Asset.url
property url: str```
Returns the underlying URL of the asset.
oh tysm
This is only for 2.0 though. If you're using anything earlier you would just use discord.Member.avatar_url
tysm
It's just memorization and me knowing how to read docs
I also understand the dpy docs quite well
wow
Just to elaborate but I wouldn't sit there for hours memorizing every little thing
I've been doing discord bots for a while and I'm willing to bet many of the volunteers here also have, it's something that comes with practice
memorizing syntax is probably the worst thing you could do, even though you should know how a language is written
programming is all about the concepts and problem solving
memorizing every function and class will do you no good
Learning the commonly used and incredibly useful functions will help a lot though
Just don't try to memorize everything
And never be ashamed to google your question/error or come to this server for help
mhmm
hello... just wondering if anyone had a nice matplotlib theme for discord?
Huh?
?
That breaks Discord tos as using themes count's as modding the client
wait, styling a image to discord colors, violates ToS?
I thought you meant the better discord themes
Anyway, that's off-topic for this channel
ahh, got it
Wdym like statistics?
we confused it with changing the theme of your discord client
i'm creating a figure in matplotlib, just figured you'd be the guys to have made a style for it
so embed seemed more seemless
thanks tho!
bruh.. i was just trying to make a serverinfo command
missed a )
OML IM SO DUMB TY

How are you defining the role?
role is None
someone fix it for me since i bought it from a kid and forgot his discor d
We don't do that here sorry
We don't fix your code but rather help and walk you through fixing it
You don't learn anything by having someone fix it for you
how i fix then
copy-paste the code here and we'll see it
dosent let me
!paste
just do that
pep8

Also string concatenation
I hope you didn't pay this person a lot of money
if not self.bot.ready in on_ready!?
from disnake.embeds import Embed
```🗿
@storm verge how much you paid this guy for this work 
🗿
pretty bad code lol
Hi! When I type the command python --version i get the Python 3.7.3 version. When doing python3.9 --version
When I try to install discord.py 2.0 using pip install -U git+https://github.com/Rapptz/discord.py it gives me this error:
ERROR: Package 'discord-py' requires a different Python: 3.7.3 not in '>=3.8.0'
Allthough I have python 3.9.10 installed? How can I fix this?
Using Linux Root btw
Hi! When I type the command python --version i get the Python 3.7.3 version. When doing python3.9 --version
cut short here bud
You need to be using a venv but that's not on topic for this channel
like 5 dollars
you mean
if commands.has_permissions(ban_members=False):
await member.ban(reason=reason)
await ctx.send('You do not have the permission "Kick members" to run this command.')
?
@commands.has_permissions(ban_members=True) means that command won't run if they don't have permissions
you need to make error handler
after command add
@ban.error
async def e(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have the permission "Kick members" to run this command.')
Imagine getting a ghost ping from here ;-;
delete that and place ban.error outside the func
why you want to ban member even if command author hasn't permissions?
with open(profile, "w") as g:
json.dump(profiles, g, indent=4)
Why this is not updating my profile file
what is profile?
are there errors?
hm
are you sure that that line executes?
mbe there are statements that block it
It executes but does not update the file
it works idk
import json
profile = "profiles.json"
profiles = {"123": "41", 532: 5234}
with open(profile, "w") as g:
json.dump(profiles, g, indent=4)
Is there a way to make sure that remove_roles() worked? Like I would like to make it so that if it doesnt remove the role, it doesnt do anything, but if it does, it sends an embed
You can check for the role in member.roles again
Or just check for an error
What error would that be?
!d discord.HTTPException iirc, but might as well check with the docs
exception discord.HTTPException(response, message)```
Exception that’s raised when an HTTP request operation fails.
commands.MissingPermissions
replace MissingPermissions with that
i am not sure that error can take extra args
but try it
i think it will work only without ban
if you want ban you need to make check inside ban command
but I still can't understand why you want that people without permissions could ban
with that you can just don't check permissions
what for is this line await member.ban(reason=reason) when user doesn't have permissions?
@ban.error
async def e(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('You do not have the permission "Kick members" to run this command.')
``` just put that
without extra args or something
I forgot how to fix
when i try to run n debug of
import discord``` it shows me "Exception has occurred: ModuleNotFoundError" "No module named 'discord'" I forgot how to fix this
Hi
the name of the file nuclearbomb gives me nuke vibes 

U do know it's a bot right
PoV: It's a command to nuke a server
its time I make one too and host it on replit 
Well
thanks a lott
which is against tos
which we do not help with
you need to check which instance belongs to which class
How would I do that?
!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).
wont this work tho?
you won't know the exact type of the parameter
it will but you need to work with them, different objects have different methods and properties
Oh right gotcha
thanks
if isinstance(query, discord.User):
if query.is_on_mobile(): print("yes")``` an example and no probs 
is_on_mobile() what is that?
Oh status right?
checks if a user is on mobile, just an example though
understood, thanks. really helped
I was jk, idk what's it for
hello
Hi
i need some help
Sure
i wanna know when does a bot gets rate limited?
-> Making API Calls repeatedly
-> Using replit
-> Using the same IP for hosting multiple bots
what if i use heroku?
Most probably won't get ratelimited
U mean VPS?
no like useing a vpn to change the ip to host
Hmm, never tried it tbh, but why use a VPN if u r hosting on yr own machine
how can i avoid getting rate limited
i host on repl.it or heroku
The context is generated in one of the functions, like send_bot_help and so on
If u r comparing the two, I would prefer heroku
so i can't use it elsewhere? only in those methods?
hmm ty (:
Yes.
also
All the send methods like send_bot_help, send_group_help and so on
thanks
what are some of the best database storage service? for free(am broke lol)
sqlite uses a file in your pc which is free
but my pc is not always on
Not yr PC, but yr VPS*
is firebase good?
wut
then if you have a vps you can use pg to host the server on the same vps

intresting
Yea, but is hella tough for a newbie (just saying)

am a newbie lol never use firebase
https://mongodb.com/ if you can't find anything else to use
Once i purge the messages from a channel using my bot the channel appears as unread for my guildmates. Is there anyway i can mark them as read after purge?
any other alternatives?
I was told by someone who wrote his bot using js uses clone functionality and can achieve this
This is beginner but how do I fix this error?
import main from Help
I have no idea
the message was to tell you what to do, why did you copy it
and thats not how you import stuff ```py
from Help import main # correct
import main from Help # wrong
You were a JS dev before?
not JS but i have worked in projects in java and cpp
oh and thx
well to be technical that syntax is only valid in ES6 modules and not CommonJS files
And honestly I haven't worked with import from all that much
Don't start it. I tried understanding all that, only to see myself coding in Python the next day 😶
yeah i feel you haha
so after importing i keep running into this
channel is None meaning the channel isn't in the bots cache so you have to fetch the channel using client.fetch_channel()
that makes sense thx
@void elm just add this statement at the top
await self.bot.wait_until_ready()
If it still doesn't work, then the ID is wrong
i did not know how to import:
from Main import client
this is new help.py file
okay, so instead of client.get_channel just do channel = await client.fetch_channel
how do i get a list, or an iterable of the messages sent by a specific member in a specific guild channel
i'm using disnake
!d discord.TextChannel.history perhaps
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
No, that returns the messages in a channel
how do i fix this
that's what i mean
You need to loop through or filter it
just if statement
check for the message author then?
i mean i guess i could
@sick birch mind helping him 🥺
oh come on
first of all get your files named properly, they should be snake_case
should they use relative imports?
Also make sure you know where each import leads to, in vscode you can CTRL + Click it
all lowercase names?
snake_cased
this_is_a_really_long_file_name.py
but if it's just one word you can just leave it lowercase
ok will convert
you could spend 2 minutes making a script that would rename it all to be lowercase instead of taking the 30 seconds to do it manually 😎
LMAO
role.members returns this list
[<Member id=813058518625157180 name='Lonely' discriminator='2334' bot=False nick=None guild=<Guild id=876740265824616458 name='Gud Meme' shard_id=None chunked=True member_count=13>>, <Member id=927806904175042560 name='karen_the_guy' discriminator='1882' bot=False nick=None guild=<Guild id=876740265824616458 name='Gud Meme' shard_id=None chunked=True member_count=13>>
how do i get just the names
from os import listdir, rename
root = '.'
for f in listdir(root):
rename(f"{root}/{f}", f"{root}/{f.lower()}")
that is something i would do if i wanted to
but done
map() it
map(lambda m: m.name, guild.members)
now make sure you don't have circular imports
i.e main.py imports help.py, but help.py also imports main.py
what i'm looking to do is to check each single message from a user for a specific word
doing it using if-statements is just too slow
how would i call help.py without importing it
for x in message:
?
one more question, is there something like saves all modifications and restarts the bot
uh that's not what i need
something like debug mode in flask
i have an iterable with the history of a channel
ok sorry
!d discord.ext.commands.Bot.reload_extension
reload_extension(name, *, package=None)```
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.unload_extension "discord.ext.commands.Bot.unload_extension") followed by a [`load_extension()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.load_extension "discord.ext.commands.Bot.load_extension") except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
i need to grab only messages by a specific user, but just doing
if user == x is too slow
ohk
You cannot
i know
I don't think there is any faster way. Discord's API doesn't provide any filters for users regarding message history, so you have to resort to getting a bunch of messages and linearly checking each one's author.

how do i fix this
Instead of importing it, why not pass it in as a parameter?
async def main_help(bot: commands.Bot):
...
Then in main.py:
# something before
await main_help(bot)
# something after
Though if you're making a help command you should refer to this <#discord-bots message>
tbh for me this is better than using cogs and more simple
i have to log off for a little bit thanks for the help everyone
circular imports dont work anyways 
Unless you scope them
found you again
Lmao
I'm everywhere 
I'mma just go from here
im bored
Go to #python-discussion or help people in help channels
Or if u wanna see some memes which gonna make u realize ur life is a drama, just go to #ot0-psvm’s-eternal-disapproval
lmao
Bro you just said 2 days ago that this is cringe
lol
Before nitro
She do be weird and contradictory
Ongg
see how nitro are killing people ||jk jk ||
why channel dry 🙁
Lemme ask a question
please




