#discord-bots
1 messages ยท Page 1021 of 1
your question is suited more for the thread
Wow cool
When you guys work with users, do you store all your user data in databases?
Discord.py models are semi serialisable at best
How would you use OOP
Currently, I have a user class, and it's methods just update the corresponding user in my database
But that involves creating an object every time I need to update it
You're just making your own ORM at that point
There's no way to store actual objects in a database, is there?
why would you need to save the data when you can store the id and get all info later, storing those in a db is just extra pain and inconvenient
That's what serializing is, but not always a good idea
What do you mean get all info later?
Fetch or get
^
I'm talking like info as in like a balance for an economy server
Just have columns for that then
columns in the database?
oh well, whats the issue then, just create the number of columns for all of them
I think we misunderstand each other lol, I only store the ID's from the Member object in my database
as you should, yes
or keys if its a json-based db
But I have many other things in the database that are not related to discord.Member
I think you're asking about how to model your data?
The best way to work with the data through object oriented programming
ORM
isnt that what data models are
I'm still a beginner to coding so I apologize if I sound like an idiot
class User:
def __init__(self, bot, user_id: int, name: str, role: ERole):
self.bot = bot
self.user_id = user_id
self.name = name
self.in_game = False
self.isBot = False
self.role = role
I have this class here, and I create objects by grabbing the corresponding info from the database
That's EXACTLY what an ORM does. You just made your own little ORM, congrats! ๐
Oh
Here's a class method
async def update_balance(self, amount):
await self.bot.db.update_one({"_id": self.user_id}, {"$inc": {"money": amount}})
Ah, NoSQL database?
MongoDB
So would this be the best way to do it? I'm basically wondering if its best to create a User object every time a command is run
Alternatives?
You could go for functional
Just methods to perform CRUD ops on your database, no dealing w/ classes or object models
I see...
So just have a method that takes the id and then updates / reads from there?
Sure, sound simple enough
Is the only difference the fact that no objects would be created
Right
Ah, but if I'm using those methods in many different cogs, I would have to import them over to each, correct?
Yes, but that's not inefficient in the way that it may take up memory
I see
could just store them all in 1 file and from file import *
Interesting. I'm basically planning to rewrite my bot this summer, but I want to make sure I do it efficiently, cause coding big projects while still learning can get messy
it can be useful to sketch out a blueprint on a physical paper
That's not something we do much anymore, but it helps me a lot
Same here though, visualization is great
I wonder. So I have a class called ERole which is basically used to setup embeds for when the user works.
I also have subclasses of ERole for the different level of role which will determine their wage.
class ERole:
def __init__(self, name, wage, work_dialogue, emoji, price, description):
self.name = name
self.wage = wage
self.dialogue = work_dialogue
self.emoji = emoji
self.price = price
self.description = description
class Peasant(ERole):
def __init__(self):
description = "Born into the lower class, destined for the upper class."
super().__init__("Peasant", 2500, self.peasant_work(), ":palms_up_together:", 0, description)
self.perms = None
self.raw_perks = None
@staticmethod
def peasant_work():
responses = ["You actually manage to scrape up some bits. How wonderful.",
"Someone donated a little more than normal. How kind.",
"You are a peasant. Feel bad."]
return random.choice(responses)
Is it efficient to create many subclasses like this when they all have the same class_work() methods?
Could I just store these levels of ERole in a dictionary and just have one class to take care of it all?
This is a common design pattern
Mine, or the dictionary thing?
Usually in languages where it's supported, you'd use abstract classes or interfaces
What you have as of now
I can't testify to it's efficiency, I can, however tell you that it's a common design pattern you see a lot
Well I'm on the right track I guess. It just takes up quite a few lines of code where it seems like it could be simplfied
If you want to learn more about common design patterns and how to implement them, I'd suggest you give the book "Design Patterns Elements of Reusable Object-Oriented Software" a read
Just their id
Since that's all you need
Read more below. Also nice pfp, that's literally my wall paper rn
I'm storing other things like a balance and cooldowns
Not just discord.Member attributes
ohh riri lovely
๐
How long is an avg cooldown for ur bot?
Right, store them in their own columns
It currently looks something like this. How many columns is usual? I'm planning on adding many many things for each user, and I don't want to have so many columns that it gets messy
That's where table joins & FKs come in handy
One way I've thought of is having another collection for each category of thing. For example, for users Farming, I have a farming collection, and I might have a separate collection for mining etc.
Lol
It also seems like you have discord-related data in there like "isBot" and "name" which you can obtain from the ID
I'm doing exactly what you suggest, once I look it up I realize I'm doing it.
I have another table where a shared column is their id
the name is primarily so I can edit user data in the database without having to cross check ID's
because that would be a huge pain lol
Leverage that against the extra space used up
I frequently change things though, since I'm still developing it. Although I suppose I could just copy ID's and filter through the DB by that ID
OH MY! If I used table joins, does that mean I wouldn't have to do this thing??
async def hook():
bot.mongo_client = AsyncIOMotorClient(data['mongo_url'])
bot.db = bot.mongo_client['discordbot']['users']
bot.dbpets = bot.mongo_client['discordbot']['pets']
bot.dbfarms = bot.mongo_client['discordbot']['farms']
I uh, don't know if NoSQL databases have joins
As that's really only a feature of relational databases
@commands.has_role("Admin") # This must be exactly the name of the appropriate role
async def addrole(ctx):
member = ctx.message.author
role = get(member.guild.roles, name="Verified Male")
role = get(member.guild.roles, name="[M] 18+ Verified")
role = get(member.guild.roles, name="Verified Female")
role = get(member.guild.roles, name="[F] 18+ Verified")
await member.add_roles(role)``` when i mention the role to give to the user it gives a different role
So how do i make it give the right mentioned role?
Use \n in the description field for a new line
and for this, put
>before the text
And please, be original and don't copy other bots 
Yeah you might definitely get nuked
โ
@nextcord.slash_command(guild_ids=guild_ids)
async def ark_ban(self, interaction : Interaction, gamertag : str = SlashOption(description="Enter the user's gamertag.")):
server_ids = [1065, 1051, 1048, 1040, 1047, 104, 1047, 104, 10456, 10470, 1042, 1049, 1059, 1050]
if (not interaction.user.guild_permissions.administrator):
embed = nextcord.Embed(title="`โ` `System Exception Error!`", description="**Exception Error, Checklist:**\nEnsure user permissions are met.\nCheck the API's current status.", color=3066993)
embed.set_thumbnail(url = "https://i.imgur.com/FmzHoKr.png")
await interaction.send(embed=embed, ephemeral=False)
return
else:
headers = {"Authorization" : key.nitrado_key}
params = { "identifier" : gamertag}
async with aiohttp.ClientSession() as session:
for id in server_ids:
url = f"https://api.nitrado.net/services/{id}/gameservers/games/banlist"
response = await (await session.post(url, headers=headers, params=params)).json()
print(response)
embed = nextcord.Embed(description=f"**`>`** **`โ
- System Success:`**\nThe user have been banned!\nResponse: `({gamertag})`", color=3066993)
await interaction.response.send_message(embed=embed, ephemeral=False)
Can someone help with this? The command works fine -
Whenever I use it, it takes about 5s-10s to get through the for-loop. Though before it finishes, it tries to send the embed at the end. It turns out being...
"The application did not respond"
Would I use a defer() or how should I go about it?
@commands.has_role("Admin") # This must be exactly the name of the appropriate role
async def addrole(ctx):
member = ctx.message.author
role = get(member.guild.roles, name="Verified Male")
role = get(member.guild.roles, name="[M] 18+ Verified")
role = get(member.guild.roles, name="Verified Female")
role = get(member.guild.roles, name="[F] 18+ Verified")
await member.add_roles(role)``` when i mention the role to give to the user it gives a different role
Errors?
Because you never have a role parameter in your command
Right, sorry.
[Bot] nextcord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
I believe it's bec it responds before the loop is complete, not sure if that's right
Try defering
Probably want to do async def addrole(ctx, role: discord.Role):
Then you can add_role(role)
Defer is just await interaction defer() right?
interaction.response.defer()
Right under the async def ark_ban ?
Cuz discord kills the entire process after like 4 seconds of your bot not responding
Sure
Okay, wasn't sure if it was to go somewhere else
ok one more is it await ctx.remove_roles(role) to remove a role from the user?
as well as define ctx
so await member.remove_roles(role)
Or define a member
yh lemme know if it works
member: discord.Member?
Yep
Congrats
03.05 05:34:07 [Bot] File "/The Hideout (Development)/Source/nitrado.py", line 38, in ark_ban
03.05 05:34:07 [Bot] await interaction.response.send_message(embed=embed, ephemeral=False)
03.05 05:34:07 [Bot] File "/.local/lib/python3.9/site-packages/nextcord/interactions.py", line 679, in send_message
03.05 05:34:07 [Bot] raise InteractionResponded(self._parent)
03.05 05:34:08 [Bot] nextcord.errors.InteractionResponded: This interaction has already been responded to before
Would I need to put a followup at the end?
interaction.followup() should return the webhook yes
and you can .send() on the webhook
So, just put await interaction.followup.send() at the end?
In theory
Yep, it worked ๐
Thanks so much!
Poor dinosaurs gonna go on a rampage without their master
hi can anyone give me a example of how to use Select ui ?
@commands.command(name="help")
async def help(ctx):
embed = discord.Embed(color=000000, title="VENOX ANTI-NUKEโข")
embed.set_footer(text=f"Venox anti-nukeโข | Ping {int(round(client.latency * 1000))}ms!")
embed = discord.Embed(
title=" | Help, Prefix:_",
description="testing"
)
embed.add_field(name=f"**misc**", value="")
embed.add_field(name=f"**security**", value="")
embed.add_field(name=f"**commands**", value="")
msg = await ctx.send(embed=embed)
``` is this correct?
try it?
yes
bot is saying command not found
did u removed the default help command?
nope
then remove
in ur bot instance
help_command = False
done, still not working
show ?
what?
where u did
do help_command = None
(command_prefix=prefix, intents=intents,help_command=None)
like this
or do
bot.remove_command("help")
anyone
in which line?
u forgot self
thats a bad practice, very bad
thank you
@slate swan
thanks :D
oh sorry, I forgot that you used disnake...
np
ye lol
import nextcord
from nextcord import slash_command
from nextcord.ext import commands
class C(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
@slash_command(guild_ids=[927234027277135923], description="Test command")
async def my_slash_command(self, interaction: nextcord.Interaction):
await interaction.response.send_message("This is a slash command in a cog!")
def setup(bot):
bot.add_cog(C(bot))
slash cmd not showing
Make sure the guild Id is correct and your bot can use application commands in the discord developer portal
Although idr if the last one is needed
from nextcord.ext import commands
Not needed
for commands.Cog?
Good
You need to invite the bot correctly with the right scope, that's it
Nothing to do with the developer portal
i invited with applications.commands scope
+it was able to make slash cmds when i was using dpy with same bot
not working with nextcord
do we need to sync here too?
do embed.add_field(name='Ends at:', value=f'{discord.utils.format_dt(datetime)}')
Warning (from warnings module):
File "C:\Users\Akai\AppData\Local\Programs\Python\Python38\lib\site-packages\nextcord\health_check.py", line 20
warn(message, DistributionWarning, stacklevel=0)
DistributionWarning: discord.py is installed which is incompatible with nextcord. Please remove this library by using pip3 uninstall discord.py
This couldnt be this reason right?
also you made a typo, it's minutes, not mintues
i dont want to uninstall yet
time to make an embed command!
@client.command()
async def help(ctx):
embed = discord.Embed(color=000000, title="VENOX ANTI-NUKE:tm:")
embed.set_footer(text=f"Venox anti-nuke:tm: | Ping {int(round(client.latency * 1000))}ms!")
embed = discord.Embed(
title=" | Help, Prefix:_",
description=" | help" \n
" invite"
)
embed.add_field(name=f"_misc", value="Shows the command related to bot")
embed.add_field(name=f"_security", value="Shows The Bot Features")
msg = await ctx.send(embed=embed)
``` is this correct according to the screenshot?
use \n to change lines
where?
!e print("changed\nLine")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | changed
002 | Line
?
@slate swan check now
discord bot invite link with permission set to 0 (no permissions) it will still be able to read and send message, is there any purpose putting the permission in the invite link? Since it adds the additional step on inviting when there is nonzero permission?
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
help?
await it
@slate swan correct?
i dont know
ok
regular expression, its a library
you can do it, its just a better way to use regex (regular expression) here since you want the id of the mentioned user otherwise you'd have to do a lot of stuff instead, but you need to have an understanding of how it happens
oo
i already have many things imported
idw to let my bot explode
for checking errors in an isinstance, like if isinstance(error, commands.NotFound). how can I pass several errors at once to do the same thing?
if isinstance() or isinstance()
i think
The second argument of isinstance takes a tuple too.
thank you
how do i do it
Just. Learn some basics of regex, it's very useful when u have to clean some data before using it
ok :/
any source?
!d regex
There are vids on yet
idk whats that
Yt*
imma just stick to traditional method
whats the full import name
import regex? @paper sluice
Someone can give an example of a bot and cog setup for the new discord version
The python's regex library is actually named "re", so do import re.
okok
!d datetime.datetime.strftime | You can use this to format the datetime object, take a look at https://strftime.org/ this cheat sheet for the supported format.
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
It's just making your setup function asynchronous and awaiting the add_cog method
And awaiting your load_extension
hi im class and i want to await something how can i
@bot.event
async def on_message(message) :
if message.channel.id == 970895283250675813 :
data = message.content.split(" ")
user = re.sub("\D", "", data[4])
print(user)
userid = bot.get_user(str(user)) or await bot.fetch_user(str(user))# Call the method to add it to database or something
db[userid + 'cooked_pogchop'] = db[userid + 'cooked_pogchop'] + 50
# Do anything else here that you want to do
await bot.process_commands(message)
!async
Concurrency in Python
Python provides the ability to run multiple tasks and coroutines simultaneously with the use of the asyncio library, which is included in the Python standard library.
This works by running these coroutines in an event loop, where the context of the running coroutine switches periodically to allow all other coroutines to run, thus giving the appearance of running at the same time. This is different to using threads or processes in that all code runs in the main process and thread, although it is possible to run coroutines in other threads.
To call an async function we can either await it, or run it in an event loop which we get from asyncio.
To create a coroutine that can be used with asyncio we need to define a function using the async keyword:
async def main():
await something_awaitable()
Which means we can call await something_awaitable() directly from within the function. If this were a non-async function, it would raise the exception SyntaxError: 'await' outside async function
To run the top level async function from outside the event loop we need to use asyncio.run(), like this:
import asyncio
async def main():
await something_awaitable()
asyncio.run(main())
Note that in the asyncio.run(), where we appear to be calling main(), this does not execute the code in main. Rather, it creates and returns a new coroutine object (i.e main() is not main()) which is then handled and run by the event loop via asyncio.run().
To learn more about asyncio and its use, see the asyncio documentation.
await blahblah
class Newbie007():
def __init__(self,bot : commands.Bot,s : commands.Context):
Wtf
huh
Your spacing triggers me
yes
Your spacing also
no
then
Why do you have a bot and s arguments in that init
bro learn python
what's wrong with ctx?
ur whole code is wrong
ok
You're indexing higher than what's inside the list
Cokecan/pepsi help me pls
Cokecan
where can i learn cogs?
Don't do this
MY INDENT
Help him
What
Several people help me
ya
๐ฆ help me
lol what help do u need
@loud junco @alpine notch help me
i want to await
@loud junco
i want to fetch
fetch what
ping pong
pls help
ding dong
i wanto to fetch channel
fetch channel???
or msg
channel id or what
you cannot change lines in a normal string
get_channel().fetch_message()
=.=
this is corocan
looks so cursed
i need it await
what corocan
pls help
corocantaine that needs to be await
oo
coroutine*
async ur class?
how
async class URCLASS
and what are you trying to do
hack nasa
he is struggling to async and await
๐ gl with that
struggles to async and await but wants to hack nasa
go to html discord server
add async infront
nu
๐คฃ
async int(Newbie007):
huh
ok
newbie, what are you even trying to do ๐
await
what in the world is the significance of a class there?
:/
i opened the chat and the first thing i see is async init, wow
async on Class Newie(Newbie007):
@loud junco like this
go back to ur chemistry exam study HEHEHEEH
NONONONONO
then Class async on Newbie(007)
do u know what async does?
yes
what does it do?
takes my brain cells
aight, im leaving earth, bye guys
!d async
why should we use async
byebye
why?
then why do u wanna use it
but u dont even know what it is
why not normal function
then it show error tob and something was never awaited
and Enable tobac prefrs nfor enabvle suck sdjg
like that
Asynchronous programming is a technique that enables your program to start a potentially long-running task, and then rather than having to wait until that task has finished, to be able to continue to be responsive to other events while the task runs.
javascript is easy
wow i started from javascript
shessssh
like 1 for ban
1 for ban
1 for kick
1 for ban
yes
Command raised an exception: NameError: name 'urllib' is not defined
You can only make 20 bots with a single account iirc
this chat never makes sense
typo i think
u mean urlib?
i created with my alts
5 alts
yes
HWHAWHWAHAW
noice problem solved
no
that time when your life doesn't make sense to yourself
@client.command()
async def meme(ctx):
memeApi = urllib.request.urlopen('https://meme-api.herokuapp.com/gimme')
memeData = json.load(memeApi)
memeUrl = memeData['url']
memeName = memeData['title']
embed = discord.Embed(title=memeName)
embed.set_image(url=memeUrl)
await ctx.send(embed=embed)
import it
who are you why are u where did u come from
and its blocking, use aiohttp instead
Yeah why i didn't help
aiohttps
what?
Left it all for sarth when he came
!pypi aiohttp
There's no s
i dont have server sorry its a server framework
for any library you want to use in python, you need to import it first
discord.py is completely based on it.
deez nuts
import urllib like this?
no
yes
invalid syntax
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
my exam is tomorow
?
now help me
!e ```py
import urllib
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
see invalid syntax
You're not helping
[no output]
seriously learn things first before suggesting something you dont know about
im asking for help but nobody help me im so sad
im Newbie007 that was trolling u all
since i comed in the chat
thanks sir working*
Hi
welcome back sparky
๐
Clash royal
e
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
how to quickly translate large text into another block?
!d str.split
split and send them seperately
nvm that wont work
seggs
I was wondering why you suggested that
async with aiofiles.open("ticket_configs.txt", mode="a") as temp:
pass
async with aiofiles.open("ticket_configs.txt", mode="r") as file:
lines = await file.readlines()
for line in lines:
data = line.split(" ")
client.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
Yes Verlac. Seggs
async with aiofiles.open("ticket_configs.txt", mode="a") as temp:
IndentationError: unexpected indent```
!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
use string slicing
I tried every indentation it doesnt work
!e py a = "a long stringgg" first_5_chars = a[:5] print(first_5_chars)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
a lon
like this
Why is client.ticket_configs not indented then

The context manager is indented for no reason
because there is not indentation error for it
Unindent the context managers
Ig thats wrong still
async with aiofiles.open("ticket_configs.txt", mode="a") as temp:
pass
async with aiofiles.open("ticket_configs.txt", mode="r") as file:
lines = await file.readlines()
for line in lines:
data = line.split(" ")
client.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
Hello
Thanks
Alright, I'm creating a bot, but for some reason not all of my slash commands load in. All of the commands who looks like this loads in:py @slash_command(guild_ids = ids) async def add_autorole(self, ctx): but when it looks like this it doesn't load in: ```py
@slash_command(guild_ids = ids)
async def remove_autorole(self, ctx, role: discord.Option(discord.Role, "Choose a role.")):
What is discord.Option?
hi how can i async a class pls help
That is pycord
๐ฟ
Wait is it named discord.Option?
Yeah, and that's what I'm usjng
hi how can i async a class pls help
Yes
What
They don't have pycord in their docs
Sad
there is nothing called an async class, first learn what async does before spamming this question
Hi ryuga
๐
several people said there is a thing called async class
Who
several people
there isn't its only functions
then async with , for?
dude....
ehh? async contextmanger?
can i do like
class Newbbie007():
def __init__(self,bot : commands.Bot,s : commands.Context):
self.bot = bot
async def dis():
yes, but why would u want to do that?
why not?
i want to fetch
fetch what?
channel
huh? can u explain what ur trying to do?
no
the accuracy ๐
I don't really suggest this but:
class Foo:
async def __init__(self):
# now you can await stuff here
async def __new__(cls, *args, **kwargs):
self = super().__new__(cls)
await self.__init__()
return self
Or if you mean "trying to await something outside async function", then you can use asyncio.run(async_func()) or if there's a running event loop already, you can use loop.create_task(async_func()).

lmao
2.69
ok
He wants to use a async method inside the init
He's trying to fetch a channel
why do you wanna do that...?
oh wait lmao, i did
i printed the function
lol
but nvm, async init errors out
intellisense did to be clear
are you inside a cog?
yes
or a class?
im subclassing'
then why dont you create a botvar
i have
then whats the issue
await
!e
import asyncio
def bar():
print('lol')
class Foo:
async def __init__(self):
return bar()
async def __new__(cls, *args, **kwargs):
self = super().__new__(cls)
await self.__init__()
return self
asyncio.run(Foo())
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
lol
fetch_x are asynchronous
yes
how
idk
but i want to fetch channel when i call the class
why are you calling the class
i want
Why
u can just await bar if bar is async
oh wait, I just meant instantiating not running it with asyncio
uk.. how about to make an async function then create task in init? @nimble plume
i maked another async function insidide the init
i mean.. this is about subclassing bot class, right?
Cog
just confirming
ooo i see
WTF am i readin
u know
lmao
We don't know
me who got brain damaged at this point
duck dont copy me
wait this is confusign me wtf
!e
async def bar():
print('lol')
class Foo:
async def __init__(self):
await bar()
async def __new__(cls, *args, **kwargs):
self = super().__new__(cls)
await self.__init__()
return self
print(*(await Foo() for _ in '_').__anext__())
@paper sluice :white_check_mark: Your eval job has completed with return code 0.
lol
+1
+1
LMAO
ah I see
ill make a while a ==1
and then it will run an aync function
ill change a to 1 in my class
and it will work fine
Starting to slip to esoteric territory
!e
async def bar():
print('lol')
class Foo:
async def init(self):
await bar()
async def __new__(cls, *args, **kwargs):
self = super().__new__(cls)
await self.__init__()
return self
@nimble plume :warning: Your eval job has completed with return code 0.
[No output]
Wait what? How tf
i got brain damage
i'm trying to understanding too 
same reaction
Ryuga pro
expecially i'm trying to understanding what the hell of use this should have
I am not thinking that
lmao
(await coro() for _ in '_') makes a genexp, then we maunally call __anext__() on it and it runs
I'm thinking HOW tf did he make the new and init async without any errors
hi how can i await inside __init__
well you can create async method 
otherwise d.py would not work
python is too dynamic
i never saw an async __init__
help what do i do
i want to use await inside __init__
but why?
and i would've never thought that someone would use an async __init__
i want to hack nasa and there is a coro

(await <awaittable_object>() for _ in '_').__anext__()
i cant understand
yeah very funny
im not even gonna "not recommend" this
same. :)
ill delete my python file
ยฏ_(ใ)_/ยฏ
nobody helping me
ill simply put that async in my cmd and then pass the message object
how to make it not stand out?
what ๐ณ
u dont want it in bold?
yea
put it in the description of the embed
the translator works poorly
or just dont use an embed
i need it to be one line
wdym by that?
i need it to be in one line, can i leave out the title value?
๐ฆ
wait
yes
it work
thx
Guys, I forgot, how to run the bot in terminal, I just remember only old way
python3 discord-bot.py
of course it says an error, please say to me, correct command which must I write in the terminal
I installed this in the cmd before all commands:
pip install discord.py
what's the error
um im not sure what to do
i want like it create options according to list
ids = [1,2,3,4,5] disnake.SelectOption(label=,description='Nothing', emoji='๐ฉ')
for label in ids:
view.app_option(disnake.SelectOption(label=label,description='Nothing', emoji='๐ฉ'))
no its add_item, not option
options = [
]
how to make it so that if the user is not muted, it will write "user is not muted"
# unmute
@commands.command()
@commands.has_permissions(manage_messages=True, administrator=True)
async def unmute(self, ctx, member: discord.Member):
emb = discord.Embed(description=f":white_check_mark:Member **{member.name}** has been unmuted, have a nice chat!", colour = discord.Color.gold())
embed=discord.Embed(title =f"You were unmuted on the server {ctx.guild.name}")
mutedRole = discord.utils.get(ctx.guild.roles, name = "muted")
await member.remove_roles(mutedRole)
await ctx.reply(embed=emb)
await member.send(embed=embed)```
Check if the mute role is in the users roles
@slate swan are u subclassing view?
async def make_embed(ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Waiting for a title')
title = await client.wait_for('message', check=check)
await ctx.send('Waiting for a description')
desc = await client.wait_for('message', check=check)
await ctx.send('Waiting for a image(URL ONLY: https://i.imgur.com/...)')
img = await client.wait_for('message', check=check)
embed = discord.Embed(title=title.content, description=desc.content, color=0x72d345)
embed.set_thumbnail(url=img)
await ctx.send(embed=embd)```
can someone test this code for me?
how do i write it?
u wrote
embed.set_thumbnail(url="img")
instead of
embed.set_thumbnail(url=img)
- get the mute role
- if .. in user.roles
thx
got it thx
i m at school rn and i was doing that
This command is correct
Workdir is probably incorrect
And what error does it give
Oh sec
python3 : The name "python3" is not recognized as the name of a cmdlet, function, script file, or executable. Check the spelling of the name
, as well as the presence and correctness of the path, and then try again.
string:1 character:1
- python3 discord-bot.py
-
+ CategoryInfo : ObjectNotFound: (python3:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
This error
try using py since windows usually has that namespace
Try py and python
If doesn't work you didn't add python to path
It's done on setup or via editing some system stuff which idk about
Don't you have to add the select options into Select first and then add Select to View?
how to add
did you see my error?
Easy way is reinstall python and put "add python to PATH" checkmark
But seems like you managed to launch it
No
!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.
well you gotta install it first to use it..
Put your traceback to there
pip install discord-py-slash-commands
???
No error
I think you need something like this
select = disnake.ui.Select(options=[disnake.ui.SelectOption(label=label) for label in ids])
view.add_item(select)```
Can you say me how, full command
please
but... it's very important.
I need slash commands
I don't recommend this library for slash commands
ERROR: Could not find a version that satisfies the requirement discord-py-slash-commands (from versions: none)
ERROR: No matching distribution found for discord-py-slash-commands
^
Use dpy 2.0 or fork like disnake
The implementation of slash commands in disnake is pretty easy, here's example of non cog implementation
import disnake
from disnake.ext import commands
bot = commands.Bot(intents=disnake.Intents.all())
@bot.slash_command()
async def hi(inter: disnake.ApplicationCommandInteraction):
await inter.send(f"Hi {inter.author.mention}")
bot.run("token")```
how do i write the name of the person who sent the message?
The userโs username.
!d discord.ext.commands.Context.author
Union[User, Member]:
Returns the author associated with this contextโs command. Shorthand for Message.author
thx
where error?I write 1 command, and it sends an attachment to infinity in private messages and chat
# mute
@commands.command()
@commands.has_permissions(manage_messages=True)
async def mute(self, ctx, member: discord.Member, *, reason = "No reason provided"):
guild = ctx.guild
mutedRole = discord.utils.get(guild.roles, name="muted")
emb = discord.Embed(description=f":white_check_mark:Member {member.name} has been muted!:bee:", colour = discord.Color.gold())
emb.add_field(name="Moderator:", value=f"{ctx.author.mention}")
embed = discord.Embed(title=f"You were muted on the server {ctx.guild.name}", description =f"Reason:{reason}", colour=discord.Color.gold())
if not mutedRole:
mutedRole = await guild.create_role(name="muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await member.add_roles(mutedRole, reason=reason)
await member.send(embed=embed)
await ctx.reply(embed=emb)```
It's your for loop
You're looping through all of the guild's channel then sending the embed in dms for every channel
Why do you have a for loop
!d discord.Member.timeout
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the
given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have the [`moderate_members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") permission to
use this...
use this instead
what if my bot has a big delay?
add_role and timeout has the same endpoint so that won't matter
if you mean the request delay
Uh, anyone here who got nitro? Not the classic one
I want to test if on_member_update is fired when someone changes the guild pfp
i write the mute command, and he responds after 10 seconds
define invisible users
you mean lurkers? like hunter right now?
๐ i c u
kek, how
alr
but then how
๐
i refuse to believe this
Huh
presence updates?
member updates? USER UPDATES? what is it?
i don't wanna play hot and cold
๐ซ tell me rn
kek
i will figure it out
kek
hmm
69
I knew someone would say 69 lol

I was very tempted myself tbh
idk what you're doing but I guarantee that is not the best way 
cya
so many (((()))))
say_goodbye()
tell_a_lie()
and_hurt_you()
the urge of running the !ot cmd
network issues?
imma make a >is_lurking <member> command
We must find the secrets
u muted ur own bot ๐คฃ
jkjk
I also must make this
i will send code after a bit
disnake.utils.format_dt(dt, /, style='f')```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Response from what?
its been a long time my friend
80% accurate hmmm
payloads sent from discord
anonymous did you even check it, that it differed for an offline user and an invisible one?
Test with me
gg
Kek
i mean ur question
hi
!d datetime.datetime.strftime use this to format the time
datetime.strftime(format)```
Return a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see [strftime() and strptime() Behavior](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior).
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
seccd = round(error.cooldown.get_retry_after())
mincd = 0
hrcd = 0
rseccd = 0
rmincd = 0
if seccd > 59:
rseccd = int(seccd % 60)
mincd = int((seccd - rseccd) / 60)
if mincd > 59:
rmincd = int(mincd % 60)
hrcd = int((mincd - rmincd) / 60)
else:
rseccd = seccd
await ctx.send(f'''
Dont spam :/
Try again in another **{hrcd}h {rmincd}m {rseccd}s**
''')
```i did this
A hole
the heck is this
double 7 single O is searching the internals so hard
What in the fuck
yes but you can just use timedelta
Why are you manually doing the cooldown
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
The humanize module would be so nice for this.
i remember doing the same
people shows me after i did this
well the timedelta or humanize module is better to use
and easier too
but i already did that
fine fine
๐โโ๏ธ yus
idk what else to add to my rpg bot
No, per-guild avatars are not retrievable via gateway, so it's not visible in edits and on_member_update would not be dispatched.
Edit: Yes, on_member_update is dispatched when a guild avatar changes, a docs update was pushed recently.
Ouh
What? Yes it is, a guild member update event is dispatched when the server pfp changes
here's a payload for that; the last line has avatar which is the new guild avatar, which you can see is different from the one in the user object
Yes but on_member_update doesn't dispatch member avatar update
you have to do it via API untill devs add it, if they would add it
But it literally just did
here's the payload for it https://workbin.dev/?id=1651575550167197
Bruh on_member_update is triggered with those changes
that's evidently not up to date
bruh it's the latest 
Yes, per-guild avatar is on the GUILD_MEMBER_UPDATE payload fields, but that event doesn't get dispatched when the per-guild avatar changes.
But again, it literally just did lmao

I'm watching the raw events and when I change my server avatar the event is dispatched
you don't
keep it open
;)
anyway, just wrote an ENTIRE COG that listens to events
ITS NOT CLOSING
and determines if a user is afk or lurking
well, if the user doesn't perform ANY actions, it can't determine anything
what gw version are you in?
kekw
regardless, behaviour is consistent across v6 and v10, I definitely receive guild avatar updates (i did just manually change it to gw v10 to be sure)
is it worth it to buy hacker plan on replit
no
for bot hosting? no
some example of good vps?
like vps u all use
aws free 
its good enough for proof of concept, you wont run a 1k guild bot out of that
https://www.scaleway.com/
Based in Europe.
https://www.digitalocean.com/
US-based.
Considered by many to be the gold standard.
Locations available across the world.
https://www.ovh.co.uk/
France and Canadian locations available.
https://www.time4vps.eu/
Seemingly based in Lithuania.
https://www.linode.com/
Cheap VPS.
https://www.vultr.com/
US-based, DigitalOcean-like.
https://galaxygate.net/
A reliable, affordable, and trusted host.
which one should i use
tested and yes workies
digital ocean?
have a look at all of them and their prices and choose according to your needs :)
ok
oh, well, time to talk to Danny I guess...
Hello vco
Personally I'm a fan of Linode; digitalocean is quite expensive and glaxygate while cheap has some substantial drawbacks when you read the terms
no ones gonna say hi to xcirno๐
that said I have my own server which I use so I dont have recent experience with any
hi xcirno 
Hello okimii
If you want substanial drawbacks look at contabo
What's contabo
"quality vps and dedicated server" with "substantial drawbacks" and "incredible prices"
German vps company. Sells "hi-powered" vps's for like 6 euro a month.
Specs include:
8 Gbs Ram
4 vCores
256 Gb Solid State Storage
And some other stuff
๐
that's better than what aws gives, what are its major drawbacks?
Personally I havenโt had any problems with it except their slow and amateur support.
fair
How amateur
Like do they just send you to google when they don't know how to fix your problem
Normally, across more notable platforms like digi or aws. Those type of specs are more of a luxury product. And would cost a significant amount of more money than 6 euro.
"Good support costs extra, troubleshoot yourself now bai bai."
Idk but those specs for only 8 US dollars doesnโt seem ethical without some type of catch
Even if itโs behind the scenes.
i sent it from my phone so probably a different unicode ch somewhere
just retype it
hi, actually I don't mind at all ๐ (but don't be offended if I don't reply though cause I rarely come here)
someone help me with this please
Just build a server by yourself like I did ๐
What the hell are those indents
Well i had it fixed last time but i cut the code and put it on the notepad so i now i forgot how i fixed it
You pressed shift + tab
Put your coroutines inside an async function
That code makes no sense
I pressed tab only
Tab moves code -->, shift + tab moves code <--
Whats Coroutines?
"async expressions"
At least you fixed indents
All async expressions must be inside async functions
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=False, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate
`check`. If a `check` is not provided then all messages are deleted
without discrimination...
Like that?
Best practice would be subclass bot and put all your setup stuff into setup_hook method
async with and await can only be inside an async def func
class MyBot(commands.Bot):
async def setup_hook(self):
# do your stuff here
client = MyBot(...)```
Better to name variable bot as well but up to you
is this the tutorial
You can figure it out from examples folder
No
oh ok
Examples + docs is a good way to learn it
https://github.com/Rapptz/discord.py/tree/master/examples
hi, i am facing a problem with the permissions for my bot
it can't add a role
- Bot's role higher than the role

- Bot's role higher than the member's role

- Bot has admin or manage role permissions

Yet i still face this issue
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "/home/container/griselda_blanco.py", line 153, in on_message
await _function.voteFunction(int(userID))
File "/home/container/griselda_blanco_cogs/functions.py", line 70, in voteFunction
await member.add_roles(role)
File "/home/container/.local/lib/python3.10/site-packages/discord/member.py", line 1012, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 495, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
what is the command
or can you show the source code
Uhhh
This is a tricky one
he didnt even show the source code XD
well
role_id = vote_assign_roles.get(voteCount)
if role_id is not None:
role = get(guild.roles, id=role_id)
await member.add_roles(role)```
Eh, well yea... But those are the most common issues
Please use guild.get_role instead
i mean i don't see the issue in the code lol
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
will it make any difference?
Traceback (most recent call last):
File "C:\Users\thoma\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\thoma\OneDrive\Desktop\discord server bot\Bot2.py", line 28, in on_ready
client.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
IndexError: list index out of range
Its faster
async def on_ready():
async with aiofiles.open("ticket_configs.txt", mode="a") as temp:
pass
async with aiofiles.open("ticket_configs.txt", mode="r") as file:
lines = await file.readlines()
for line in lines:
data = line.split(" ")
client.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
The list doesn't has 3 (or 4) elements
well, my main concern is the permission thing rn XD
the role is an integration ( booster role/bot roles)
nope
hm
just a normal vote role
may i see your code?
async def voteFunction(self, memberID:int):
guild = self.client.get_guild(int(guildID))
member = guild.get_member(memberID)
role_id = vote_assign_roles.get(voteCount)
if role_id is not None:
role = get(guild.roles, id=role_id)
await member.add_roles(role)```
SO just delete the list 3?
^
Why use discord.utils.get?
!d discord.ext.commands.Bot.get_role
its Guild.get_role
Fuck yeah just realized
but that should not be the Issue
You are not allowed to use that command here. Please use the #bot-commands channel instead.
alright i will use it lol but like why does it say Missing access
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
can you try printing rhe role variable to check if it gets the correct role?
alright
Yeah i know i'm just suggesting improvements
i agree
Since discord.utils.get is slower
tho i did re-copied it to make sure before coming here
doesn't really matter since it's a private bot
Are you doing it to yourself?
yeah for a server
Damn i was late ๐
Are you an admin or the owner
admin
it printed the right role
Are you the same level of admin with the bot?
the bot is higher
^
Can you add roles to your bot?
yeah
Doesn't that mean you have more power than the bot
I mean i can add roles to the owner of the server lol
as long as it's lower than my highest role
the bot should be able to do the same
