#discord-bots
1 messages · Page 65 of 1
I just have this error
extensions = bot.cfg.get('core.InitialExtensions')
for extension in extensions:
bot.load_extension(f'cogs.{extension}')
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension(f'cogs.{extension}')
how can i fix it?
await it
also u can await only in an async function
ie u can await that only in async def
@shrewd apex how can I make it so that when the button is clicked , information is written when the user has registered and when he has logged on to the server ??
wdym ?
He is talking about user info
Kota Factory ft. Sarthak
With buttons
so u want when a user clicks a button it send an embed? with user info?
just use the interaction.user object
yes. Each button is responsible for its own information
!d discord.Interaction.user
The user or member that sent the interaction.
use this
the dedication
@shrewd apex what's the difference between user and memeber btw?
member is in a guild user dms
skadoosh~
🤯
@shrewd apex I've already used it and then I didn't succeed, now everything works...
Yes bruh, the last fight was full of epicness
mhm
imagine talking about movies in a python related channel
Congratulations
it's discord bot channel so it's fine
🤣
Every part has its own epic scenes tho
🏃 before mods arrive
In this channel we often talk about meaning of life, creation of the universe and the eternal fight between good and evil
In part 2, him reflecting the explosives 💀
It's sooooo me 💀
Also I 🤓
@shrewd apex And is it possible to make it so that everything is written in numbers, that is, 2.11.2012 ?
1st one was just him literally throwing his weight around
🤜
!d datetime.strftime
Double datetime
!d datetime.datetime.strftime
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).
But him turning from being a mushy boi to op boi was epic
👌
... sure
no one dares to refute 🙏
Yes sir 🫡
@shrewd apex ERROR
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 59, in voicetime
created_at = interaction.user.created_at.datetime.datetime.strftime("%a %b \n %B %Y")
AttributeError: 'datetime.datetime' object has no attribute 'datetime'```
💀
intense music starts playing in the background
How would I make it so when a user sends a message in a certain channel, the bot fowards that message to another channel and deletes the message the user sent from the first channel>
@shrewd apexthank you of course for your help. But my God, who writes documentation for python, which individual is brainless, describes everything so terribly
You can define the message and delete it from that channel then provide other channel and make your bot send this message like-
msg = message
await message.delete(msg)
Then fetch your channel and send the msg to that channel
terribly?
Yes, it's terrible. Each documentation is worse than the previous one
Ok 🙃
People can have different opinions
@cerulean shale it just seems to me that in order to understand this documentation, you need to learn not python, but the Orc language.
Man pls don't ping every single time
Ah thank you
🫡
did guild.create_webhook get removed
check the docs
it should be there tho i remeber making an event for it in my logger yesterday
That was never a thing in the first place
it was
You can only create a webhook from a channel
It's impossible to do Guild.create_webhook
And if you don't believe me you can check the official API as well as all versions of discord.py documentation
It doesn't exist, and never has
Guild.channel does not exist
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
no guild.create_webhook
webhooks are associated with channels, not guilds
alr mb
How to make user information written in the format 02.11.2016 ?
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
for example you could do utils.format_dt(user.joined_at, style="d")
and it will give you when they joined in that format
😝
no. not a fig does not work.
huh
@discord.ui.button(style= discord.ButtonStyle.grey, emoji = '2️⃣')
async def lvl(self, button, interaction):
joined_at = interaction.user.utils.format_dt(interaction.user.joined_at, style="d")
await interaction.response.send_message(
embed = discord.Embed(description= f'Присоединился: {joined_at}', colour=0xF1C40F),
delete_after=60
)```
ur trying to get the date the interaction joined lmao
which wont work
user: discord.Member=None
if u want the user put this in ur args^
and ur defining joined at
u dont need to do that
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 67, in lvl
joined_at = interaction.user.utils.format_dt(user.joined_at, style="d")
AttributeError: 'Member' object has no attribute 'utils'```
ERROR
ye because ur doing user.utils
@discord.ui.button(style= discord.ButtonStyle.grey, emoji = '2️⃣')
async def lvl(self, button, interaction, user: discord.Member=None):
await interaction.response.send_message(
embed = discord.Embed(description= f'Присоединился: {utils.format_dt(user.joined_at, style="D")}', colour=0xF1C40F),
delete_after=60
)```
try this
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 68, in lvl
embed = discord.Embed(description= f'Присоединился: {utils.format_dt(user.joined_at, style="D")}', colour=0xF1C40F),
NameError: name 'utils' is not defined```
import utils ffs
discord.utils
from discord import utils 
or that
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
i sent it earlier
🙏
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\osnov.py", line 65, in lvl
embed = discord.Embed(description= f'Присоединился: {utils.format_dt(user.joined_at, style="D")}', colour=0xF1C40F),
AttributeError: 'NoneType' object has no attribute 'joined_at'```
get rid of the =None
id=None> row=None> -
I don't even have this in my code.
How to use pagination with buttons for a help command?
@slate swan@shrewd apex@slate swan Thanks for the help
what did I do
np
oh I thought that was sarcastic lmao
he mightve meant asher
indeed 
Import pagination from discord.utils
ew
Okay thanks
!pypi reactionmenu if u just want a readymade paginator
A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.
that's not even a thing
@slate swan I had a lead of both
Oh-
??
Nvm ig
nextcord has that afaik
@slate swan what do you plan on nuking 💀
Oh that might be it then
NOTHING
caught in 4k?
5k
thats literally not even python worthy kek
calling 911
no please!
meh
!ot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
🚪 🏃
okimii
You yoinked that code?
Well your arg is number but you are using msg, and since msg ain't defined, it won't work
Copied the code?
you ment interaction.user.id?
I am asking YOU dude anyways
yes?
??
😔
stop calling me that were literally 2 different people
Yeah sure
was that supposed to be sarcastic?
Yes
i figured
How do you print hello world with base64 @primal token
🎉
what type of question is that
you want do what? compare codebases or sm
mines probably better kek
🔥
hi can someone help me test something? i think its a bug with the python bot
if you do !user_info it gives you wrong info
can you help?
and you
sure
!user_info

Created: <t:1523220614:R>
Profile: @sick birch
ID: 432643355634171905
Joined: <t:1624113052:R>
Roles: <@&815701647526330398>, <@&787816728474288181>, <@&267630620367257601>, <@&764802720779337729>, <@&463658397560995840>, <@&897568414044938310>, <@&988801794668908655>
Messages: 31,254
Activity blocks: 5,131
Total: 0
Active: 0
Looks right
hmm but it is not showing correct info for noid : |
the hell are you trying to do with my info?

trying to get ur ip maybe?
kek

!user_info @primal token
You may not use this command on users other than yourself.
bruh
yes comand is broaken
Lmao
i dont need UR info but comand is not working fr U
ic privacy 🙏
Paranoid🙈
just show him he worked so hard to see 😔
“fck u”
-Endysis
though everyone can see the bot's response
ohh how i can see other ppl address and sosial sercuity number then ?
💀
if he were so smart he could just use the search bar and check that channel for my name as ive already done the command
by fooling them onto ur bed 
And what is the point of this if the command is like !user_info <user_or_message>?
Kind of gets rid of the need for that argument at all unless your a moderator
hmm
Hi there so I am trying to do button and this keeps happening
cannot import name 'Locale' from 'discord.enums'
Could someone help please I am trying to put a button on a message then if someone clicks it (no limit on how long after the button was created) it will respond
so modrator can see the user adresses?
And when I click it
From what I've seen in the source code
ohh do the modrator take bribe
But I about a year ago i used to do on_button_click but now its all changed
why i cannot reaction here
Only helpers+ have reaction perms here and in pygen
Because #discord-bots and #python-discussion are the most active and and reactions are hard to moderate
and no
: (
Why? It’s not like reactions enhances your experience in any meaningful way
Hi there I keep getting this error
ImportError: cannot import name 'Locale' from 'discord.enums'
When I go to import
from discord.ui import View, Button
says PPL with reaction perms
u only cherish stuff once it's lost 😔
I mean, I never use it unless im trolling as a joke
!e
eval.__call__("".join.__call__(chr.__call__(int.__call__(a, base=2)) for a in "01110000 01110010 01101001 01101110 01110100 00101000 01011111 01011111 01101001 01101101 01110000 01101111 01110010 01110100 01011111 01011111 00101000 00100111 01100010 01100001 01110011 01100101 00110110 00110100 00100111 00101001 00101110 01100010 00110110 00110100 01100100 01100101 01100011 01101111 01100100 01100101 00101000 00100111 01010011 01000111 01010110 01110011 01100010 01000111 00111000 01100111 01010110 00110010 00111001 01111001 01100010 01000111 01010001 00111101 00100111 00101110 01100101 01101110 01100011 01101111 01100100 01100101 00101000 00100111 01100001 01110011 01100011 01101001 01101001 00100111 00101001 00101001 00101110 01100100 01100101 01100011 01101111 01100100 01100101 00101000 00100111 01100001 01110011 01100011 01101001 01101001 00100111 00101001 00101001".split.__call__()))
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World
good luck reading it
kek i think PPL want it precisely coz it's rare in this channel flex and all ig i do too ngl
nice
and yeah it gets encoded in base64 its just everything is in base 2
i am one with the computer
Please could someone help me
even stack overflow does not know and I am scared xD
there never was on discord.py
prolly some fork u used
All I am doing is from discord.ui import View, Button and it comes up with an error
do u have 2.0 installed
Ummm
How do you install 2.0?
All I did was update it
pip install git+https://github.com/Rapptz/discord.py is this it
2.0 has been released, so you can do it from pypi

I'm guess you did
pip install discord --upgrade
Right?
pip3 install --upgrade discord
Requirement already satisfied: discord.py>=2.0.0 in c:\users\orang\appdata\local\programs\python\python39\lib\site-packages (from discord) (2.0.1)
Do you have another library that uses the package name discord installed, like pycord or disnake?
It really is Okimii
You definitely have some third party library clashing with the main one
This is what happens when you upload a package that monkey patches another
literally how
This is also why venvs are useful
🥺🥺
because im the same skill level which i doubt as okimii it doesnt mean im him lmao
Idk bro everyone thinks your Okimii
okimii had chinese fairytale guy pfp too
That’s racist 😭
Ok so I deleted all the discord but the error is comming from the discord folder
As shown in the picture
They are Japanese
but i have more experience than him......?
Idk he knows a lot
who said i dont?
ok
Try doing
pip uninstall discord
pip install discord --no-cache-dir
Thanks alot it worked 😁
👍
while True:
if num=='2':
letters=3
user = "http://tiktok.com/@" + ('').join(random.choices(string.ascii_letters + string.digits,k=letters))
f = open('names.txt', "a+")
f.write(f'{user}\n')
f.close()
#start of 3l and 3c part
if num=="2":
f = open('names.txt', "a+")
f.write(f'{user}\n')
f.close()
time.sleep(0.2)
print(Red+bold+f'[Taken!] {Red+bold+user}/')
if random.randint(0,10000) < 36:
print(Green+Green+bold+f'[Available] {Green+bold+user}/')
code doesnt even run sadly
Idk why
Impossible from what i know.
Plugins already exist for it
what is num?
Or if you want to do it yourself you can make a minecraft plugin using JDA or similar
Oh then it's going to be difficult
Sure but you might want to up the interval
At least a few minutes
there are apis
A google search for "minecraft server status API" will turn up many results
So you don't flood the server with requests
In short, so that you don't sorta DDOS it
You're basically carrying out a DoS attack
That is why ratelimits are in place
DOS*
if youre spamming a host with requests thats basically is a DOS attack depending on the motive
I'd do a minute just to be safe
and thats where cloudfare comes in lol
Ngl, since its only 1 request per 5 sec, he should probably be fine
But I remember seeing a module somewhere which has some events regarding people joining, leaving and so on, tho i don't remember where
It has detailed documentation
What does the documentation say?
Well that's the first thing you should do
Nice!
Doesnt matter dww
did you solved your issue?
Yes
bot.pool is None
nice
You know what I'm gonna say... what does the documentation say?
I doubt that, let me take a look
Ah, see?
Documentation is the first place you should go to
... the documentation has an example for you
I wish every module and API had docs this great
it's not the greatest but it'll do
how can i do something like this in nextcord? i mean that there are fields requiered
Better than those API's where u gotta try and test the different results
The one underneath that
Gives you a comprehensive example response payload
By using the players key
Everything you need is inside the documentation
MyBot doesn’t have that attr
you did
print(type(bot.pool))
bot.pool = pool
what do you expect?
Hey ryuga mind checking dms rlq?
bot.pool is wrong it should be self.pool in order to bind the pool to the instance
Also you shouldn't be constructing pools inside of on_ready
That sort of thing should only be done once during life-time
You are misunderstanding how classes work
Later once you have an INSTANCE of MyBot set as bot, then bot.pool will work yes
But since you are in a method of MyBot you have to access the instance VIA self
So inside of the class, change it to self.pool and outside of the class it'll work fine using bot.pool if bot is MyBot()
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Ryanh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "F:\[bots]\MyChemicalCult Bot\bot.py", line 98, in on_message
await client.process_commands(message)
AttributeError: 'Bot' object has no attribute 'process_commands'
Getting this error using the pycord dictionary
intents = discord.Intents.default()
intents.members = True
client = discord.Bot(intents=intents)
Intents are enabled on the bot
which ide is that
looks like the same file editor thats on my friends vps panel
You need to change it there yes, but also inside of on_ready
Again it's inside of a method...
What do you think?
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Ryanh\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "F:\[bots]\MyChemicalCult Bot\bot.py", line 98, in on_message
await client.process_commands(message)
AttributeError: 'Bot' object has no attribute 'process_commands'```
Getting this error using the pycord dictionary
```py
intents = discord.Intents.default()
intents.members = True
client = discord.Bot(intents=intents)
Intents are enabled on the bot
Then change it, why ask me? I've already told you to change it inside of on_ready
👏
hia
do you have discord.py slash commands docs?
Yes... I mean it looks like it is working does it not?
what should i import for slash command?
Other than the AttributeError but that's due to the fact your running acquire before the loop is even defined, E.g running acquire before READY is dispatched
So the error did not dissapear lol
Again refer to my message above as to why it errored... And refer to this one to fix it
If you don't do it inside of on_ready it won't require the bot to be fully ready before the pool can be acquired
E.g set it inside of setup_hook etc
And I cba to give anymore help rn cause I'm busy so I'll let you figure that out
how to make a click handler in select menu ? Does it look like a click handler in just buttons or not ?
Hi there so I have created a button but I want to have an event for when it is clicked. As right now if the bot restarts the button will not work
do you want to make a handler for buttons ?
I think so
basically I want an event when you click it and if has a certain event_id then it responds
I made a slash commands bot, should i get invite url as bot or application.commands ??
Which one ?
I believe it would be both
Alrighty, tysm
how to make a click handler in select menu ?
should be similar to how you do it in buttons
...
import discord
import discord.commands
class aclient(discord.Client):
def __init__(self):
super().__init__(intents= discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id = 693190295520673924, guilds = [773260643872145428])
self.synced = True
print(f"{self.user} olarak giriş yapıldı!")
client = aclient()
tree = commands.CommandTree(client)
@tree.command(name = "test", description = "deniyoruz işte karşim", guild = discord.Object(id = 693190295520673924))
async def self(interaction: discord.Interaction, name : str):
await interaction.response.send_message(f"Merhaba {name}, bu slash komutlarının ilk komutu ve test mesajıdır")
PS C:\Users\Administrator\Desktop\fly-bot-slash> & C:/Users/Administrator/AppData/Local/Programs/Python/Python39/python.exe c:/Users/Administrator/Desktop/fly-bot-slash/main.py
File "c:\Users\Administrator\Desktop\fly-bot-slash\main.py", line 13
self.synced = True
^
SyntaxError: invalid syntax
PS C:\Users\Administrator\Desktop\fly-bot-slash>
Missing a ) in line 12
await bot.change_presence(activity=discord.ActivityType.competing(name=f"{prefix}help"))
TypeError: '_EnumValue_ActivityType' object is not callable```
what is the competing status for this?
nevermind, i got it!
add inline=False to your add_field (assuming youre using discord.py)
alr lemme add it
This doesn't make use of any fields, it's all in the description
oh that as well
o
i got this do you guys how i can make the 0 go next to the words
e.g: completed: 0
You can't
you cant??
with fields, no
what do i need to make to it
use embed description
works thanks do you how i can make it like
print the persons who uses the commands id/name and pfp
so im using the embed desc like u said
how do i make a line break between each description
lemme send a ss should make more sense
i have it like this which is good but how do i keep adding descriptions now
Just add content to the same description with \n as linebreak
oh alr
Hello, I'm looking for creators of pokemon bots so that if they could help me with a pokemon bot with their codes or helping please
use an API

where are they?
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
from that object u can access these infos
theres so much stuff where do i find it
yeah sorry im new to python and everything lol
clue, ctrl +f " Member"
of?
@tidal hawk this?
correct place
👍
and what kinds of things are you looking for? You want to have users profilepicture and mention him?
yup
when they use the command it want to appear like this
well now look at that section
most use REST APIS that access an internal database(s) with submitted data lol
i got the descirption done i just need the name and picture now
is this bad
why?
also, is there a way to set an arg to automatically .lower()? @primal token
I can't think rn but it's prolly really easy
well you can just convert it uppon getting it
I mean like when you define the arg
how would you access the argument uppon defining it?
nevermind
ok, but how can I put custom emojis on the bot, that is, it comes out of a text from that bot
async def sasdasd(ctx, something) -> None:
make something automatically .lower()
you would need to overwrite the local variable
ioh
since strings are immutable you would need to overwrite the variable with the result given with str.lower
afaik nope
Just a weird question, if you have a tuple, then you delete it would it still print out the tuple
It would depend
How can I put custom emojis on the bot, that is, leave a text from that bot
what do you mean exactly tho?
Like
just know that mutable pointers come in play
I make a tuple, print it out, delete the tuple, and run it again
the object would be deleted if its defined inside of a variable if you delete the variable the pointer gets deleted hence freeing the memory
Ah ok, thanks
do remember that python uses a GC which if the object has no references the data gets freed making the object not accessible avoiding segfaults
Ok thanks for the info
I really do not understand lambdas and filters
And for lambdas can’t you just use definition instead
Like def
No because a lambda is an expression, and a statement def is a statement
you can but its shorter
You can't use def everywhere
no but sometimes its better to have an anonymous function over declaring one
Hence lambdas
its better having an expression than having context managed keywords
I can’t understand lambdas and filters
filter is just a function. it goes through everything in the second argument passed, inputs it into the first argument passed (which would be a funciton) and if it returns True then keep it, otherwise remove it
foo(def bar(foo: str))
``` vs ```py
foo(lambda foo: ...)
``` see the diff
Ah ok thanks
Ye the first one gets an error obviously because that isn’t the correct syntax
Actually it is
I think
I’m kinda an idiot so ye
What’s a soft keyword…
andy ment its different passing a function and a lambda object
since one is a statement while the other is an expression
Can you show me an example of a lambda and a def that would output the same thing
A soft keyword for an example would be match
How can I put custom emojis on the bot, that is, leave a text from that bot
are you sure? isnt a soft keyword a keyword that depends on its context? i thought it was but it kinda makes sense as theres not other context
Yea, read the Cpython source code and you'll see def is not a soft keyword
do you mind sending the link?
!e
def func(x):
return x * 2
print(func(2))
func = lambda x: x * 2 # you normally wouldnt assign it to a variable like this
print(func(2))
@torn sail :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 4
002 | 4
lambdas are always helpful for one liners and stuff like map that take a callable as onenof their arguments
And you don’t type return in lambdas?
nope whatever comes after the : is what is returned
Ah cool
lambdas always return the given expression
That’s for helping me understand
Ok thanks
Lib/keyword.py line 30
'def',```
Thank you
i want to learn C to understand CPython more do you guys think its worth it?
It isn't really difficult but I would suggest knowing how to read the function first of all, and knowing some bytes & pointer stuff
E.g id(object) + int.basicsize
All the even numbers
Modulo operator checks for remainders
If the return is divided by two and has zero remainders it is even
Ahh
I would say i do have a bit of knowledge uppon memory management, rust showed me about it as well how pointers work etc but the only thing that does scare me a little is syntax and memory management especially the fear of segfaults and memory leaks for some reason
I see
It's hard to segfault python in normal use cases, memory leaks can be fixed by using a profiler
Cough vagrant cough
Or GDB
ive seen some books but theyre dummy thick with 700 pages easily
sadly ive never heard of them
And rust has it's whole own thing with memory management
Sure pointers exist but they use borrow checking mostly
But using pointers & ref in rust, some people would say it defeats the purpose of rust but
i just know the general knowledge of pointers, stack, the heap and i also do know about pythons memory management but i have 0 knowledge about C's
Well that's the fun part
iirc C doesnt use OOP only cpp and C object oriented or something like that
C is not really OOP based
im not very knowledgeable on a language like C😅
is it functional based?
or is it like a mix?
mhm thats quite interesting
Well, now a days your pretty safe when it comes to memory management in C due to your kernel
What does yield do
But that is not really an excuse to use heap memory without freeing
How can I put custom emojis on the bot, that is, leave a text from that bot
Return then pause the function at the current line
Question what about learning something that uses OOP, maybe cpp would that help me understand CPython due to similarities of C and CPP or is cpp not really comparable abstraction wise? never really tried cpp so im not sure on the language's abstractions
kinda have hit a learning block and i want to step up my skills by learn a low level programming language like C, i was trying rust but im not really sure about it
CPP is more complex then C so I wouldn't be able to tell you much cause my C knowledge is far beyond my CPP one
I do know that CPP has it much easier when it comes to creating pointers
malloc calloc vs new, etc
mhm ic, its easier to make pointers with the use of abstractions or just how the language handles them?
sorry if i worded it a bit weirdly i cant really describe what i ment
It's easier because you just do, ```cpp
class Foo {
// stuff here
};
Foo *foo = new Foo;
vsc
struct Foo {
// stuff here
};
Foo *foo = malloc(sizeof(struct Foo));
Traceback (most recent call last):
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\tjdom\Dropbox\PC\Desktop\test\test.py", line 45, in on_ready
link = await channel.create_invite(max_age=300, max_uses=1)
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 881, in create_invite
return Invite.from_incomplete(data=data, state=self._state)
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\invite.py", line 316, in from_incomplete
guild_id = int(data['guild']['id'])
TypeError: string indices must be integers``` help
ah ic, CPP does keep Cs integrity for example standard data types right? its just OOP and is it any different from pythons OOP or is it a bit more complex?
looked online cant find fix
Yeah ik i just have seen claims about for example javas oop is better than pythons i guess syntax or abstraction wise?
data var is a string but you're trying to use it as if it's a dict (is data an Api response? are you converting the response to a json object?)
print(f'{bot.user}')
for guild in bot.guilds:
print(guild.id)
guild = bot.get_guild(int(guild.id))
invitelink = ""
i = 0
while invitelink == "":
channel = guild.text_channels[i]
link = await channel.create_invite(max_age=300, max_uses=1)
invitelink = str(link)
print(invitelink)
i += 1```
don't make Api calls in on_ready event
Well, with CPP it's mostly the same to python's way I guess, other than the fact with how "dotnotation" works
You have methods, these methods are bound to the class, etc
You don't get self through params rather you get it from this
E.g inside a method you'd use this->attribute
@primal token I can't remember how to get author url 😭
mhm ic
And if it's a pointer you would use pointer->attribute and if it wasn't a pointer you'd use variable.attribute
wouldnt variable still be a pointer just pre defined?
either way, thank you for your time, im going to learn cpp now!
wdym author url?
No it would be an object
Not a pointer, hence using regular dotnotation
std::string variable("something");
// verus
std::string *variable = new std::string("something");
ahhh makes sense now thank you
how tf do i do it then
What's the field at the top left of an embed? the little circle you can add
!d discord.Embed.set_author ?
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
I think
ok yeah
how
https://cplusplus.com/doc/tutorial/introduction/ this is nice
Can you not set the icon_url without name?
Embed.set_author has the name kwarg with no default value making it needed sooooo

how do i call this without a event
name="** **"
bro chill
But logically speaking, if you think about it. It would kind of be weird to have an author with no name right?
what's the point of this
are you gonna spam make invite links or something?
how to make spacing inbetween fields
you can't afaik
guild = client.get_guild(785250885391220776)
tenshi_role = guild.get_role(855870040129798164)
komet_role = guild.get_role(855869125485264926)
AttributeError: 'NoneType' object has no attribute 'get_role'
u can embed builder does
i just wanna get a invite for all the guilds my bots in 😐
client.get_role()
then use the embed builder and do it
You could probably just put everything in the description
Then you could get codeblocks and markdown formatting
nope what i did was right i found my error
the loop that included that function started before the bot was logged in lol
only use await on async functions
im just tryna run it without a event 😐
lol
does test() not work
because theres no other event I KNOW OF that i could run it on without something except on ready
You mind letting us see the code around that
of course
The await syntax is only applicable inside running async functions
Yeah so you can’t await it unless you’re in another function
wait i think im stupid
Where the error is
You can call it from the bot loop directly since it’s exposed
But I can’t see a use case for this that isn’t against standards
Had whole bunch of discussion in this channel long ago about creating invites without permissions
We seemed to come to the consensus that it is against ToS
nope thats what i got error on
So show us your code where you did that
whats the point? when bot makes invites it only works for bots
i tried before
ah yes, old syntax
So you’re literally not doing what I told you to do
That isn't true at all
It’s still valid. Should run fine
You don’t necessarily always need the context manager
in my case it was
well, they removed the bot kwarg at some point
i have literally no clue about discord.py ik only a little stuff from discord, youtube
That they did. It should be ignored internally anyway but ig it’s indicative
discord py is easiest module on py imo
I recommend you find some videos or courses regarding both OOP and asynchronous execution
D.py relies heavily on both
And even if you were able to await the function correctly you'd most likely get a NoneType AttributeError
Your relying on the cache so
how would i define role in a on_member_ban listener?
You must make sure READY is dispatched before you call
What do you mean
i just wanna run its without a event 😭
oop isnt used very often unless you use modals or buttons
What is role supposed to be?
That's why on_ready is so appetising but it's also not ideal. The best bet would just be a command
OOP is used literally to run the bot
The bot structure being modelled around a network of custom classes that have private attrs and public attrs shows the reliance upon it
instance.attribute is apart of OOP
@commands.Cog.listener("on_member_ban")
async def anti_ban(self, guild, user):
reason = "Anti-Nuke System | Banning Members"
whitelisted = db.find_one({ "guild_id": guild.id })['whitelisted-users']
antinuke = db.find_one({ "guild_id": guild.id })['anti-nuke']
if antinuke == 'off':
return
banned_users = []
async for i in guild.audit_logs(limit=1, after=datetime.now() - timedelta(seconds=5), action=discord.AuditLogAction.ban):
banned_users.append(i.target)
if self.bot.user.id == i.user.id:
return
if i.user.id not in whitelisted:
await guild.edit(i.user, roles=[])
await guild.ban(i.user, reason=f'{reason}')
for target in banned_users:
try:
await guild.unban(target if target != i.user else target, reason='Anti-Nuke System | Unbanning User-Banned Users')
except:
pass
@wicked atlas @winged coral
python and the whole dpy framework is based on OOP
Please explain what your initial question is alluding to
await guild.edit(i.user, roles=[])
i have tried on_ready, running it separatly both do not work 😐
Right, so what do you want roles to be?
my error is
2022-08-28T23:04:37.551170+00:00 app[worker.1]: await coro(*args, **kwargs)
2022-08-28T23:04:37.551171+00:00 app[worker.1]: File "/app/cogs/antievents.py", line 37, in anti_ban
2022-08-28T23:04:37.551171+00:00 app[worker.1]: await guild.edit(i.user, roles=[])
2022-08-28T23:04:37.551172+00:00 app[worker.1]: TypeError: Guild.edit() got an unexpected keyword argument 'roles'
Yeah because you’re editing the guild
every role the user has?
You want member.edit
hi, i'm new to python and was interested in making discord bots but i can't seem to fix this problem, can someone help me?
Intents is a required kwarg
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
Im trying to get the bot to remove every role the member has
Users don’t have roles
use for loop
Since this event is a ban event you don’t have a member
members
You have a user who isn’t in the guild
Don't roles get removed when a user gets banned anyway?
Yeah Lol but its better to remove all roles the ban
The member doesn’t actually exist anymore but it might be in the cache. You can’t do anything to them though because they’ve been banned
I think you’re misunderstanding when this event fires
Is this heroku?
stripping every role the member has then banning = less members banned
@wicked atlas not really py related but you should use .hover on github logo and yt it looks better imo
dude what
If it is just fyi heroku is shutting down all free dynos come nov 28th
re read my code
It’s a on_member_ban listener
i could, theres a lot of things i could fix up on it, but im just too lazy to
💀 i want it to strip every role the member who banned the other members before the bot bans
LOL
obvi
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/latest/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.
its pointless they lose roles on ban
The mod loses their roles
^
o
Some sort of nuke prevention
You’re basically using the wrong function
Guild.edit edits the guild not the user
if u dont trust user dont give them ban perms, ez
!d discord.Member.edit
await edit(*, nick=..., mute=..., deafen=..., suppress=..., roles=..., voice_channel=..., timed_out_until=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the member’s data.
Depending on the parameter passed, this requires different permissions listed below...
You want the above function
its a public bot
so i shoul change my
Guild.edit edits the guild
E.g. changing the guild name
Member.edit edits the member
@heady citrus You can ask here instead of DMing, i’ve gtg now anyway, someone else could reply
But no, you don’t change the parameters
You change the function call where you edit
roles = bot.get_guild(guild_id).roles
for role in roles:
role_object = discord.utils.get(roles, id=role.id)
try:
await role_object.delete()
except:
pass```delete all roles in server
- should check what
Bot.get_guildreturns as its prone to NoneType errors - why are you getting a role object if
Guild.rolesreturns a list of Role objects already, youre literally using attributes of a Role instance to get itself - why the bare exceptions ?
😭
await Member.edit(roles=[])
no matter what i do i get this error ```Traceback (most recent call last):
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\tjdom\Dropbox\PC\Desktop\test\test.py", line 59, in on_ready
print(await channel.create_invite())
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 880, in create_invite
return Invite.from_incomplete(data=data, state=self._state)
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\invite.py", line 316, in from_incomplete
guild_id = int(data['guild']['id'])
TypeError: string indices must be integers
all i did this time is
on_ready gets called before the bot is actually ready, try this in setup_hook
actually try not to do anything in on_ready since that sometimes gets randomly called
You said the opposite
on_ready is dispatched when, 1) Gateway sends READY dispatch 2) All guilds are chunked and accounted for
on_ready is when the bot is fully cached and ready
setup_hook get's called before the bot even connects to the gateway iirc
you got it mixed up, you could ask in the dpy server, and they will ensure you to not do anything in on_ready
When did I say to do something in on_ready???
can i just get a invite to there
discord/client.py lines 529 to 530
To perform asynchronous setup after the bot is logged in but before
it has connected to the Websocket, overwrite this coroutine.```
tag from dpy
Did you... even read what I said?
Andy is right but setup hook is called after setup
I did, thats not my point tho
It’s just a one-time alternative to on_ready
setup_hook is literally called before the bot even connects
Its not an alternative to on_ready because it isn't cached yet
If you were to do get_guild in setup_hook you'd get None
no you wouldnt
Yes you would
I disagree
Refer to this?
I literally use setup_hook on all my bots for things like this bc on_ready wouldnt work
If you aren't connected to the gateway during setup_hook how exactly did you get something from the cache????
i just wanna make a invite 😐
Please explain to me this my mind cannot comprehend
?
You don’t have to connect to the gateway to get guilds
The gateway fires events
Once the bot is logged in it can retrieve guilds from the REST
But you’re right, it isn’t gateway connected
is this it?
???????
You literally don’t lol?
That's not how discord.py works with the way you said it no
Yes it very much is
Discord.py chunks when connecting to cache the channels...
It does not make a GET request for all channels
?????????????
So get_channel inside of setup_hook would retrieve from a GET request???
yes a non-coroutine function making a request in discord.py
that logic is sound...
setup_hook is a event right
No you’d need to subclass
No but the way are doing technically works
setup_hook is called before ready is dispatched and ready is when the channels are cached
setup hook is coroutine
telling me it works does not help because everything i have tried has not worked
https://github.com/Rapptz/discord.py/blob/0981f122afc69772a3541b205b382256cc8f3d1d/discord/client.py#L908-L925 and if you look at the source code there is no SIGN OF THE REQUEST which you refer too
You’d fetch not get
I’m just saying that u can set the setup hook that way. I just got here and I have no clue what ur asking
Refer to what the user was doing in their code
I'm only using get_channel as a means to show it's grabbing from cache
I didn’t even look at the users code, I got here and read the convo between you and the other guy
I was arguing the lib behaviour not the user implementation
The other guy is saying that setup_hook is called once the bot is cached and ready to go, where as on_ready is dispatched when the bot is not ready
Do you believe that statement whole heartedly?
I said you’re right like years ago
god
I think you’re looking for a reason to argue
??
Because it works in setup hook, my bot is running next to me and does just that
i just wanna make a invite 😭
Sorry, could you send your code again
guild = bot.guilds[0]
channel = guild.text_channels[0]
print(await channel.create_invite())```
Well setup_hook is a coroutine belonging to the class, it fires once but it isn’t an event. You could subclass it or I think you could just setattr on the instance but you’d do that before the login is called
Traceback (most recent call last):
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\tjdom\Dropbox\PC\Desktop\test\test.py", line 59, in on_ready
print(await channel.create_invite())
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 880, in create_invite
return Invite.from_incomplete(data=data, state=self._state)
File "C:\Users\tjdom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\invite.py", line 316, in from_incomplete
guild_id = int(data['guild']['id'])
TypeError: string indices must be integers```
bruh
you dont always need to subclass the Bot class just to overwrite a method
pretty redundant
bot.event uses setattr so it works
ima just give up this is to complicated
I also said the alternative just after that lol
Ahh right okay fair enough then mb
Yeah you’re right ofc it does, dk why I didn’t clock that
like this right?
Still really shouldnt be the first option you should always provide the easiest way as you can see hes already frustrated by his current impl which is quite simple
mmm it totally works...
well ive tried that doesnt work
I gave both solutions one after the other bro please 😭
lol
Also with logging you quite literally see setup_hook called before it even connects
why does not work for me 😦
Same error?
What a waste of time, poetry took me 22s just to install discord.py so I could test
nothing never called
yes
what version
⁉️
v2.0.1
😐
Like that matters at all though???
ima check my version
your issue isnt about versions?
I mean setup_hook didn’t exist on old versions I suppose
im not sure what your issue about is exactly but it seems like caching etc
Bro, even if you re-install it, it won't work
setup_hook is called before cache get's populated
iirc the order of callings is setup_hook > on_connect >on_ready
Idk why that person keeps telling you to use setup_hook it literally does nothing to fix your problem
then what do i do 😐
I don't use disnake, sorry
should replace the greenhearts value with javascript
discord.js has a good reputation being up to date
But djs server has sooooo many damn announcements almost every single day bruh
And they mention everyone 💀
you don’t say
💀
Looks slightly indented
Maybe it's inside of the function/class above?
You're sure? It looks indented in the image
Can you send a larger screenshot?

Sure
bottom of the cog
Because I don't see any other reason
Probably forgot to save or something
As a side note you shouldn't be making a database connection inside of the cog
There are a million things you "shoulden't do" when making a bot but only like 3 really matter
right
it matters when your database crashes or your data gets corrupted or your bot goes offline in production
There is no production
This is discord bots
No one cares
Save the connection object as a bot variable, get your cursor from there
i cant install disnake?
Sure there is. The server you send off your bot to deployment for, the one with CI/CD pipelines setup
devops tool that I think everyone should learn how to use
Does nextcord have setup_hook or something similar?
That's the perfect place to do it, then
I mean there's no need for a task
same stuff in here
because usually the hard way is the better way
Hey
You're close, just remove the nested function declaration
and do something like self.conn = ...
I would recommend using create_pool instead of connect as using a connection pool will handle connections for you
How can i make all roles delete Incase of sortings
async def setup_hook(self):
async def login():
this is a nested function
async def setup_hook(self):
...
you don't need a function inside of another one
Complex choices with many abstractions arent exactly hard
Class?
That was targeted towards @slate swan , sorry
🤓🤡
async def setup_hook(self):
self.conn = await aiomysql.connect(...)
You can then access the connection object wherever you have access to your bot instance
Thats your only response? 2 emojis when im trying to see what your point is to have a discussion about?
Low tier shitposting
You just said "hard choices arn't hard"
Where?
Im not gonna talk to someone who is just trying to look smart lol
who said im smart?
🤡
I think this person is just trying to stir up an argument by combating anything we say
Because i want to have a discussion with you doesnt mean im smart it means im a human🙈
Just don't interact with them and move on
Average discord-bots behaviour
Robin just become a mod
I'm just trying to save you all the headache
No, you can remove your login function inside of the cog
As long as you have access to bot, you have access to the conn obj
i start school tomorrow again so i doubt something could make my headache hurt more
oh not at all i already started i just took a week off
sadly i need to go back
ah, usually people blow off days at the end of the semester but you do you
yeah and you need to tweak the remaining code so it uses bot.conn instead of that
In the case of your cog, self.bot.conn

I took a few days because i was sick calm down im not that irresponsible.....
Yea in your settings class
Whever you access the connection you change it to self.bot.conn
Can someone help me? I added this at the time i created the bot, thats about 1 month ago and now it wont add the gif to the embed anymore since i switched to a hoster... Is there any way i could upload it as a file in the embed?
Yes
Also I don't see why you need your function to return both the connection object and a cursor
if you just obtain a cursor from the connection object again
No you did it wrong
self.bot.conn is already an instance of the connection
You don't need to call it, or set it
It's already set, etc
conn = self.bot.conn # this is not necessary, but easier to type
async with self.bot.conn.cursor() as cur:
...
Which? The async with will work fine
nextcord probably doesn't support setup_hook or you did it in the wrong place :wah:
Yea make sure you create the connection before you do load_extension
If it doesn't you've already subclassed so, just override start and super
class A(commands.Bot):
async def start(self, token: str) -> None:
# do aiomysql connect here.
# do load_extension here
return await super().start(token)
you also already have the setup_hook function so you may as well just do await self.setup_hook() inside the start override
u can also make the token a default param that way in main.py u won't even have to pass the token
what happens if you pass your own account to the bot when running?
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=".",intents=intents)
@bot.event
async def on_ready():
print(f"We have logged on as {bot.user}")
bot.run(my_account_token)
just a curious question.
Well with an unpatched version of discord.py it'll error straight away
This is because an actual user has no intents avaliable
Actually no I remembered wrong I think, you just won't see any messages as a self bot, etc
Due to intents
either way if you run your token its againts TOS even if you dont do any automation discord discourages the use of unofficial clients
I can only see discord.py as an actual "client" if I squint really, really and I mean, really hard
that sounded really weird, but it can probably be a client if you handle events etc, maybe a CLI discord client?😳
i tried a CLI discord client worked in go but it wouldn't recognize my token lol
You'd have a shitty client at best, can't send friend requests' etc. Almost every other endpoint you use as a user account will instantly lock your account, etc
i think that would be a good idea for me to do it in cpp for my first project after i actually read the whole tutorial and docs
The second part is pretty true from what I've seen with my friends testing
who said you need friends? how would it lock my account, they notice automation or the use of unofficial client behavior?
There are some endpoints with checks from what my friend told me
If you request them there is a likely chance you'll just get locked when using a user-account
yo guys whats the unoffical discord api server invite?
