#discord-bots
1 messages Β· Page 167 of 1
await inter.response.defer()
await inter.edit_original_response("string")
lol i think u need to start with basic python b4 discord bots
inter.?
yt moment
π
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
i prefer that over repl users asking how to host free
i dont prefer either both at bottom of my list
ok be honest, bot = construct or client = construct x)
@shrewd apex i had added this
but , still problem
its just let me enter 10 line of message
bro i am 99% sure u copy pasted and have no idea whats happening
make sure with 100%
Just putting async in front of function definition doesn't make the whole function asynchronous
bro discord.py is async and just adding async to def dosent make stuff async io operations are blocking by io it includes read writing to files
How do I get a bot to connect to the voice channel to which a specified user is connected?
yeah
exactly!
do u have problem with that?
requests is blocking π·
use aiofiles
!blocking
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

whatever
channel_id whats that it dosent exist in the local function evironment
Use aiohttp, it was installed along with discord.py
think of functions like a vending machine it only knows and has what u enter in it and gives u some output
so u either pass channel_id in params or u declare it in the function
@naive briar all urs π
imma dip
It blocks your whole program when it's fetching the webpage or API until it's finished
How can a discord bot make my server more interesting and make people talk?
it doesn't even get a new message every 10 hours
how?
thank you for your help @shrewd apex @oblique sorrel @rare echo
i had to convert it to f-string , maybe its help me
or
use embed for that
a discord bot wonβt be groundbreaking for a server, if your server isnβt building a community then itβs just like every other server
as much help as mobile is
πΉ
iβll be back in ab 45 and can help 
wdym
await site.json()
yes you can
wait no
xd
because you need to await it too lol
u can do
idk i forgor lol
you can double await it.......
data = await (await session.get()).json()
hm?
.....
can somebody join a VC with me so you can help me
!d aiohttp.ClientSession
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
can somebody help me we're discord bot
ye?
doesn't run
you need to install discord.py
pip install discord.py
in terminal
still doesn't run
I did what you said
show me
ok
@naive briar handle π«
I tried to send a notification when a user connects to the voice channel with this code, but I get this error message. What should I do?
```RuntimeError: asyncio.run() cannot be called from a running event loop``````py
@bot.event
async def on_voice_state_update(member, before, after):
if before.channel is None:
toast('test')
define channel_id = in the function
py -m pip install discord.py also u need intents
the whole traceback please
toast seems to be something i had seen in kivy why are u using it here?
if its related
Traceback (most recent call last):
File "C:\Users\zarus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "d:\Other\ffgai-main\ffgai-main\discordbot.pyw", line 25, in on_voice_state_update
connect()
File "d:\Other\ffgai-main\ffgai-main\discordbot.pyw", line 19, in connect
toast('Hello Python\U0001f40d')
File "C:\Users\zarus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\win11toast.py", line 375, in toast
asyncio.run(toast_async(*args, **kwargs))
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\asyncio\runners.py", line 33, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop```
whats this toast function?
with dpy? odd
yeah so u can use toast_async
which toast uses in backend
and await it
I was able to execute it!!!! Thank you so much!
np
π
π₯
πͺ


Oh what was the issue?
one of my send_messages was a send
Ah that explains
Also, it shouldn't have been Messageable.send()
Since Messageable means its a simple command (because Messageable represents a TextChannel)
yea the preceding object was wrong as well
What is the discord.py version u r using?
And please say u pip installed discord.py and not discord
and what did u pip install?
pip install discord.py?
or pip install discord
Uh, run pip show discord.py
and pip show discord
yea lol
and can u try pip uninstall discord?
Okay so the package is correct
I wish you had access to that lol
when r u running the function?
on_ready or what
Okay here comes sarth
He gonna solve yr queries
missing sentinel error in requests usually get raised when rest is not ready
Nice name u got there sarth
request as in, u r sending an API request when the bot is not ready
API Request as in the fetch method
not the requests module
he is talking about web parsing or getting information from a web api.....
that's why catgal suggested aiohttp since this lib is not a blocking func
whats happening here
what's blockink func? simply if u use requests module seems ok if the website's API is too good like doesnt even get host error then ok..... but some of them web need to get temporary down thus the API in this mean time if u use requests it will try to get info from web but it will fail as because the web is down, so using aiohttp which is asynchronous not gonna break ur other codes π
ig i tried π
"url"?
oh the actual web url?
first time i see site without http
then ggood
π€
but u sure mate u defined the url?
ok gooooood...
π nice
ppl dont even know legb scope rule
what about channel_id?
I don't think you can send request to a website without http/https in the endpoint url
0.o
i am trying to explain from past few hours
Lmaoo
pretty sure i have two-three replies
?
still uses https π
Bro
free host
;-;
tf host?
yep
internet protocols
man be using 0 indent like flexing pentagon co ordinates
bro read up legb scope rule
bro u said 0 indent
here is scope
Lmao
phew phew
x = 7 # 0 indent
def foo():
... # 4 indent
π
maybe he meant like
x=y
y=z
i have no idea
ok so whats ur problem send the traceback
outside the deco :)
protocols
Good job
you should use f-string dawg this thing looks weird
i cant able to see anything cuz of yellow lines lmao
cookie
altho those comments unecessary
Go Study
lol i tried
0.o
what happened
when writing wyvern
class just got over
erroneus stuff half the time
self study
and it thought it was right
^
you're the one having boards in 1.5 months
its blocking anywhere u use it
STOP
in async context
PLEASE
yad mat dila bhai
and you gotta score 90+ no?
STOP IT DAMN IT
im just motivating
YOOOOOOOOOO 90+ big brain
bro so eveytime u instantiaate the class it bloacks
that leads to a chain reaction which triggers depression
zamn
thats the intention
exactly like this
Seriously bros lets get serious

i am on good mood ngl
ik aim for 99 then get 95+
Not u
need ducky here
π¦
Okay I am out before I lose my cool
im too tired to study today, will just code all night
lore lore
asher! lore
parents: SCORE MORE U MF
too slo
yeah ik knew, predictable
5 second cooldown
ofc bro i am asking over a year now
ok btw we are going to off topics
my bro just made this channel off topic respectttttttttt
its not gonna tell u and happen u wont even notice but it happens
we are doing this since it exists
@mowderwators
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ayo this role name is cool
reminds me of someone sarth uwu
me feeling good after the bone died from my throat π
shudup
:3
reminds me of a meme
sarth missing his partner
sadge
?
they were partners in crime and in an uwutastic relation
cause those things get triggered after the bot is running
WTF uwutastic? π
||Ashley||
*samarth
laughing irl π€£
Wait she and sarth..........?
and uwutastic
we found out later it was a he
whAT
RIPPPPPPPPPPPPPP
his name was samarth
Lets move this to ot everyone lmao
you need some sleep
π here
That was my alt bro π
wtf
wtf
lmaooo
Lmao sarth needs some some rest now
LOL
stop hacking into others github accounts
plotwist
I didn't, it's clearly mine
demn twist
@shrewd apex update me either in DM or in #ot2-never-nesterβs-nightmare what happened π₯Ί
proof
πΉ
wait bro i had nightmares over this
me shaking for some reason πΏ
long story short:
ashley updated GitHub profile,
turns out to be a guy,
heartbreak for guy named savvy
@odd mango bro
Now who tf is savvy
and everyone who was called uwu
Anyone willing to help test a discord based game I've made using discord.py? It requires at least 3 players (but can be tested with 2) so if anyone can help me feel free to message or ping!
friends me sarth ashley savvy and another guy
what is the issue?
just don't call that coro before the bot is running
how much time it gonna take
i dont wanna miss these ot scenes π
one round is 15 minutes, but i'd like to test 2-3 iterations. It's quite passive you don't need to be there the whole 15 minutes
#python-discussion will help u xd
I don't know if it's ok to ask there haha
wtf it's cogs not cocks lol
Is there a way to get the voice channel a user is in based on their id?
and a guild id, sure
!d discord.Member.voice
property voice```
Returns the memberβs current voice state.
How do I use my guild id? This is the current code
@bot.event
async def on_ready():
member = bot.get_user(000000000000)
await member.voice.channel.connect()```
first use bot.get_guild to get a discord.Guild object
then use guild.get_member to get a Member object
and then connect
I was able to execute it!!!! Thank you so much!
why do you want that? and how will it guess, which command is excpected to run?
if they have same names - you can make them both in one command
ctrl + f2 in ur files
and search for the name
on Mac?
Idk of there's a ctrl on Mac
Or is ur ctrl key just missing
strg
strg
goofy ahh keyboard
search for it manually
or there might be another way depending on your editor, google it
hey i need help setting up a command, i need to kick every user in my server wich has written less than like 10 messages, is it possible?
i can't find anything online about that
i guess no one has ever needed to do that
do you guys think it is possible?
Hi, I'm trying to send the date which is the given days + the time now, and another argument which is a specific member. Without the member argument it works fine, but with the member argument I get this error:
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'Member'
The code:
async def fj(ctx, days, member: discord.Member):
end_date = date.today() + timedelta(int(days))
await ctx.send(end_date + member)```
I write `.fj 5 @user`
It may has something to do with separating the arguments in the `.fj 5 @user` command in a specific way but idk
i've never tried dpy but you could get the amount of messages every user has (it's possible cuz there's bots that count top messaging users in a server)
and for the users w less than 10 messages just kick them
yeah, mee6 does that, the issue is that i need to automate the process, i can't manually kick 400 people
well a kick command over a list ig?
why cant u automate it
well if you haven't tracked each message when they were sent it would be very hard to go through every message in the server
unless there are very little messages
well end_date is a date object and member is a Member object and you are adding them? how do you want it to be sent?
oh right, I forgot to add an f string, tysm
I did not mean to add them lmao
Just prune members if you need to kick all inactive people
!e
import numpy as np
upper_brown4 = np.array([10,0,10])
print(upper_brown4.size)
print(upper_brown4[0])
print(upper_brown4[1])
print(upper_brown4[2])
print(upper_brown4[0:2])
@meager fulcrum :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 3
002 | 10
003 | 0
004 | 10
005 | [10 0]
#bot-commands
Hello, anyone know how i can do this in my code?
What library are you using?
Lemme look something real quick.
Yeah, Iβm sorry. I donβt use Discord.py.
Hopefully someone else can help.
No problem
Can i have some help, im tryna make a bot that plays music from youtube through a voice channel but i keep getting so many random errors to the point i just deleted it, can someone help me recode it?
Im doing it on Repl.it
And running the bot through UptimeRobot as a free way to keep it running
Thatβs against YouTubeβs terms of service.
il do it with spotify, soundcloud or something else then
Spotify doesn't allow that unless you've premium
i do.
SoundCloud is doubtful but possible
In general music sites don't want you streaming off platform which is why it's difficult
i think i have an app in spotify dev
okay
https://developer.spotify.com/documentation/web-api/ out of scope for this channel but here's to get you started
Anyone know? π
alr!
its a slash command option, the way to do it depends on the wrapper you use
Hello, still need this?
they are either still using prefix commands along with slash commands, or the content creator is dumb
They might be using a !sync command to sync their app commands, so a text command prefix would be needed in that case.
a !sync command isnt really a requirement, a slash command locked to a guild with owner check ( if the sync is more than just tree.sync()) or just an on_message will suffice
tbf commands.Bot makes command_prefix a required argument, so you gotta write something for it
I wonder why it comes with a default tree then
That implies you should be using bot for app commands
Yet required command prefix
so Iβm using on_user_update and I want to post to a guild that a member has updated their name/discrim/avatar
Iβm using mongo db to store guild IDs and log channel IDs
before & after in on_user_update are instances of discord.User
not discord.Member, so there is no guild
so how would I go about doing this?
Perhaps you want to use on_member_update?
that isnβt called when a user updates their name/discrim or avatar
and those are the 3 updates Iβm looking for
Ah ok. You'd probably have to loop through all your guilds and check if that user is in that guild
Have you tested locally to see if it really does/doesn't do what you want?
aw man I didnβt want to do that
I would say test on_member_update locally as it might be what you're looking for
I originally had my code for when a user updated their name and stuff in on_member_update (if before.name != after.name) and that code wasnβt being called at all
So I looked at docs
Ah yikes, looks like you'll have to do it manually then
^ like this?
Yup
The issue is when a user is in multiple shared guilds
I suppose then you'd just send it to all of them
Should actually be pretty simple now that I think about it
guilds = filter(lambda guild: user in guild, bot.guilds)
!d discord.Member.mutual_guilds
property mutual_guilds```
Equivalent to [`User.mutual_guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.mutual_guilds "discord.User.mutual_guilds")
for guild in before.mutual_guilds:
data = db.LOGGING.find_one({"_id": guild.id})
if data:
#send webhook here
sorry for the slow typing Iβm on my phone
smth like that should work right?
if before is your Member/User object. yes
alrighty ty
is that pymongo?
yes
you should be using the async mongodb driver for a discord bot (, its called motor ), you'll just have to add a bunch of awaits
!pip motor
Shouldn't your query be called via await/async syntax then?
If you are using Motor, find_one is a coroutine function. So if you don't await it you're not gonna get the expected behaviour
seems to work fine for everything else without await
Pretty sure it causes an error when I make it async
hold on let me jsk it and see
Pretty sure that means find_one is not a coroutine function then
Perhaps you are using Motor but not in db.LOGGING
And or you made that interface without having the overhead method as a coroutine function
!e ```py
async def example() -> None:
print("Hello World")
example() # note: not awaiting the coroutine.
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:4: RuntimeWarning: coroutine 'example' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
yeah I used jsk and await works fine too
this whole time I havenβt been using await tho and it seems to work fine
Iβll add await to make my code more asynchronousy.. thank you
Can you show the db.LOGGING.find_one method?
If there is no problem great, but I'm kind of curious what your function looks like in order to make it work in that way
π or maybe its "just working" but not working as it should
Iβm importing database as db, and in my database.py file, I have:
import os
from dotenv import load_dotenv
from motor.motor_asyncio import AsyncIOMotorClient
load_dotenv()
MONGO_CLIENT = AsyncIOMotorClient(os.getenv('MONGOURL'))
DATABASE = MONGO_CLIENT["Aziel"]
LOGGING = DATABASE["Logging"]
then Iβm just using find_one on that
the docs say that its a coro
pymongo?
nah, motor
the return type is from pymongo because motor just wraps pymongo in a run_in_executor
!e ```py
async def a_condition_that_actually_returns_false():
return False
if a_condition_that_actually_returns_false():
print(1) # no error, but works!
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <string>:4: RuntimeWarning: coroutine 'a_condition_that_actually_returns_false' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
003 | 1
Reading the source code for Motor and I've got to say, what the hell lmao
there can be such flukes π€·ββοΈ
Granted this is my first source dive of Motor but
Iβm actually interested on how this is working now
print the data variable here and see for yerself
hold on
From what I see Motor wraps using a bunch of base classes like Async that then wraps the synchronous function in a Future
Then it get's ran in another thread
Is that necessarily bad?
thatβs the difference between using await and not using await
Or just unorthodox
It's hard to read at least for me
whoops
Because there is so much nesting going on
didnβt crop one of them
It's not typed either
the first one of them is just a pending future i.e. regardless if the data exists or not your condition will continue...
so in short, when Iβm using if data: I need to use await otherwise Iβm gonna run into errors?
Does the pending future complete the query to your mongo DB?
as long as you want to get a result*
just checked, it doesnβt seem to now
It's a safe bet to await your Future's/coroutines, cause yea they can still execute in a way but you WON'T know when, causes issues like race conditions
That's why await is so good
for guild in before.mutual_guilds:
data = await db.LOGGING.find_one({"_id": guild.id})
if data is None:
return
async with aiohttp.ClientSession() as session:
logWeb = discord.Webhook.from_url(data["loggingWebhook"], session = session)
if before.name != after.name:
embed = discord.Embed()
embed.title = "This is an example of my code."
await logWeb.send(embed = embed)
this code doesnβt wanna post my webhook
and it doesnβt give me an error either
noted.. ty
await logWeb.send
sorry await is in my actual code
I just didnβt write it there cause I wrote that on my phone
If it neither errors nor sends an embed, then you might wanna check if before.name != after.name:
@commands.Cog.listener()
async def on_user_update(self, before, after):
for guild in before.mutual_guilds:
data = await db.LOGGING.find_one({"_id": guild.id})
if data is None:
return
if before.bot:
return
async with aiohttp.ClientSession() as session:
logWeb = Webhook.from_url(data["loggingWebhook"], session = session)
if before.name != after.name:
e = discord.Embed(colour = 0x2f3136)
e.set_author(name = f"{before.name} changed their name!", icon_url = before.display_avatar.url)
e.description = f"**Before:** {before.name}\n**+After:** {after.name}"
e.set_footer(text = "This event occured:")
e.timestamp = discord.utils.utcnow()
e.set_thumbnail(url = before.display_avatar.url)
await logWeb.send(embed = e)
my raw code
and I just changed my name
from Chaze to some random letters
Then from the random letters back to Chaze
so there is no reason it shouldnβt be called
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
me and robin had this convo earlier lol
^
Is data none?
Also your code errors when mutual_guilds is []
Because data isn't defined in the second if statement
If the for-loop never enters that is
nope
data has a value
and it should be returned if itβs none
Have you made sure your event callback is fired?
Like can you add a print/and or did you have one
Iβll try add one
"This resource is being ratelimited."

let me try my discrim
yup, itβs being fired
if before.discriminator != after.discriminator:
e = discord.Embed(colour = 0x2f3136)
e.set_author(name = f"{before.name} changed their discriminator!", icon_url = before.display_avatar.url)
e.description = f"**Before:** {before.discriminator}\n**+After:** {after.discriminator}"
e.set_footer(text = "This event occured:")
e.timestamp = discord.utils.utcnow()
e.set_thumbnail(url = before.display_avatar.url)
await logWeb.send(embed = e)
thatβs the code for sending my embed when a discrim is updated, that isnβt sent either
^ just another if statement under this code
Is this discord.py's Webhook class?
Iβm using pycord
Okay, pycord's send for Webhook is not a coroutine function
Fault on my part
I would remove the await and try again, if that doesn't work then make sure the webhook url is indeed the correct one
it is
Pycord offers support for creating, editing, and executing webhooks through the Webhook class. Attributes avatar, channel, channel_id, created_at, guild, guild_id, id, name, source_channel, source_...
should be because my on_message_delete using the same variable (data["loggingWebhook"]) in the exact same way which works perfectly fine
I don't know if the documentation is wrong or not but https://github.com/Pycord-Development/pycord/blob/91ca670dd3116a7bb195a322c930f2a8b4f0fcfe/discord/webhook/sync.py#L954-L1087
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/sync.py at 91ca670dd3116a7bb195a322c930f2a8b4f0fcfe Β· Pycord-Development/pycord
Here in the source code it's non-coroutine
I think the source code isnβt updated
cause im using send as a coroutine in on_message_delete
works perfectly fine
The link I just sent is from the master branch
And I checked the GitHub link of the documentation you sent me, it's invalid
Oh nevermind it works now?
Holdon a sec
Okay pycord is just confusing the hell out of me
There are two Webhook classes both with the same exact name
One is sync and the other is async
So I'm really lost at this point
Should probably report it to them at .gg/pycord
I think it's been fixed on the master branch
But whichever commit hash I was just looking at had two
so conclusion is itβs a coroutine right?
Should be
But I really don't know what the issue is in your code
At this point we've gone over any logic issues and it not being called
But those aren't the issue so I'm lost
pretty sure there is sync and async for webhooks intentionally
they just dont have it documented. they are really bad at documenting shit
What seems to be the problem?
ok so turns out data is None
for guild in before.mutual_guilds:
data = await db.LOGGING.find_one({"_id": guild.id})
so that is returning None
Selfbot
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
how to fix this
Selfbot
Selfbots break ToS and are against our server rules
k
lmao
Kek, so it was a logic issue there
Was suspicious of data
π
yeah pycord server said "Well that's not going to work since you're reassigning the value of data in every iteration."
so Iβm ummm a bit stuck
I donβt really wanna use mutual_guilds anymore since that is only cached guilds
so not sure what to do
So, I am using aiohttp to save the contents of a URL to a bytesIO object so I can send it as a file with discord.py and for some reason it just keeps erroring out, either valueerror null or request entity too large
When would it not be cached?
The cache is populated on gateway connection, it's updated when given certain events, etc
It will almost always be up to date, that is granted you don't block your own bot
so all mutual guilds should infact be cached?
block my own bot?
ah I see
That might cause your bot to have a "dead" cache
kk, noted that
right so now I will be using mutual_guilds
pycord server have told me this: "Don't reassign the value? Store the IDs in a collection and iterate over them when sending your webhook"
so thatβs what Iβm working with atm
Yea you are re-assigning the variable you set
So your data would only be for the last mutual guild in the list
well, that is because andy is very smart in the aspect of developing. so when andy explains something to someone who doesnt have the same knowledge, it may be looked at as confusing because andy is explaining something with the assumption it can be understood as simply as he/she understands the topic. so yeah it creates confusion. thats why you ask more and more. the more you ask the more you know. dont walk away misunderstanding the topic because one explanation didnt give you the knowledge needed. im sure andy would have been willing to break down the explanation.
!e ```py
for i in range(10):
foo = i
print(foo)
@pliant gulch :white_check_mark: Your 3.11 eval job has completed with return code 0.
9
so everything in for loop
@commands.Cog.listener()
async def on_user_update(self, before, after):
for guild in before.mutual_guilds:
data = await db.LOGGING.find_one({"_id": guild.id})
if data is None:
return
if before.bot:
return
async with aiohttp.ClientSession() as session:
logWeb = Webhook.from_url(data["loggingWebhook"], session = session)
if before.name != after.name:
e = discord.Embed(colour = 0x2f3136)
e.set_author(name = f"{before.name} changed their name!", icon_url = before.display_avatar.url)
e.description = f"**Before:** {before.name}\n**+After:** {after.name}"
e.set_footer(text = "This event occured:")
e.timestamp = discord.utils.utcnow()
e.set_thumbnail(url = before.display_avatar.url)
await logWeb.send(embed = e)
like so?
Actually, I'm unsure what the mutual_guilds is for exactly
But this'll use data in respects to mutual_guilds
But your webhook is the same so it'll send in the same spot everything
How can I stop my bot from replacing all the text inside the txt file with the newest confession?
Webhook url should be different for every guild
Iirc you're looking for the a mode
I would also use aiofiles
so I donβt have to loop every guild and check if the user is in it?
sup 
hi
π
y the long break 
Dont really want to talk about itπ
hunny bunny was so worried about u π
where is noid
You havent changed a bit
Let me guess, you guys thought me and him where the same person?

was i supposed to 
ofc ofc for a while
Oh didn't see that part
It should iterate through mutual_guilds then get the webhook for each
So yea it should do what you want
kek he told me about it
I mean, i guess
okie I'll become all mature from tom
we should go to dms or ot
No
too large means ur server doesnt have the ability to receive files that big
limit is increased based on server level.
Yeah I know
Who TF is this Okimii now..? @upbeat otter smh
back to back scam
istg
Whole lot of lies ik
discord is a lie people on discord are liars
lol
You being the biggest Yea you are right

I mean, everyone has lied in their life
yea but that identity thing is quite unique
huh
identity fraud 
The third text in the .txt file was answered with No in the name value. Why is it still writing it in the file? I tried to use == "Yes" or "yes": before but it also didnt work...
I literally just took a break due to some issues, how did i commit identity fraudπ
uh...? How am I supposed to know
I literally just wole up
woke
it's the same old okimmi
Why cant you spell my name yet
it's the same thing, I just happen to do that unwillingly
mk
Lies
You came back at the wrong time (if u really are oki), so yea, it's gonna take a few days
!or
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
I did, hope you guys forgive me for what i did, had some issues, which i still have, but im trying my best
Can I ask what happened?
You don't wanna ask
πnp np
(if u r talking about the identity crisis)
Why dont we stay on topicπ
That too
hunter i would think you still have the habbit of using !ot
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
yup
Im not okimii l
OH
@slate swan HI
π
How are u its been a minute
I never thought this day would come
Now who r u π
@upbeat otter smh
Ive been good, what about you!
Why do you keep pinging ash
I've been good π
May i ask, how is your OOP journey?
ash committed identity fraud
this is definitely the real okimii u can see by the spam of the pokemon emoji
how soπ
catfished sarth
ngl I havent touched it since u left
That's messed up
ikr
I thought you would've been a master by nowπ
Me too
I got busy and just stopped learning
mhm ic, where did you stopped? Iirc i was teaching you classmethods and staticmethods?
I actually need help on something rn that you might know how to do
Yup
Hllo
Sure, send a dm
add me back
π’
See, my memory isnt that badπ§
long time no see
Ikr, how are you infernum? I see you havent changrd with your cat pfps
Lmao I really haven't, and I'm alright how are you
Im doing better!β€οΈ
That's good, hope 2023 is an even better year for you
You too, i hope everyone has a good next year!
Seriously tho take all this to an OT
we really should
π
I'm not okimii wtf
Ashley
Long story but Ashley was Eevee's alt who is Ash now and all of them are one person who's a guy
eevee is ash?!?
who's a guyπ
Bro
is ash an indian dudeπ
Anyways
I have already melted my brain yesterday night by understanding this and I'm lucky mods didn't want/mute us for talking so OT so yea I'm out rn
Yea
yes!
see yaaπ
Need help with something ot
Wanna migrate from sqlite to postgresql. The code itself isn't the problem, I just don't know how to transfer data.
Ok π
is there an alternative method to sending an ephemeral message when using interaction?
huh?
await interaction.response.send_message("message", ephemeral=True)
I already used this and need to send a second ephemeral message but I get
- This interaction has already been responded to before
So im looking for an alternative or how to use two in the same thing
Returns the follow up webhook for follow up interactions.
- TypeError: 'Webhook' object is not callable
.send
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
ok
can it fetch the user which is unknown
i mean not in any mutual servers
by id
will return None
what do you mean .send? interaction.channel.send doesnt have ephemeral and user.send goes to dm
the user which is not in it's mutual servers
interaction.followup.send bro
it's not going to return None maybe
so what is best get user or fetch user
client obj only has this two methods, get_user and fetch_user u can give it a try if it can fetch the user or not which is not in mutual server
- 404 Not Found (error code: 10015): Unknown Webhook
this is what interaction.followup.send gives
give code
i got it ty
get_user will never work since it searches the cache for the user but it'll always return None since your app never loads that user to the cache as the user is unknown to the app
@light violet to get a user who isn't in yr bot's servers use fetch
ok thanks
LMFAO

also try not to use fetch so much as it makes a call to the api everytime
ohk
can somebody help me code a discord bot if yes please join the VC0
hello
discord.app_commands.errors.CommandInvokeError: Command 'create_ticket' raised an exception: TypeError: View.add_item() missing 1 required positional argument: 'item'
@shrewd fjord
u need to add an item
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
What would even be the use of that lmao
Void
nice
myview = View() not View
okay
thanks ! worked
good
hello
how can i put an button on a message?
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
is there a way to create event buttons ? or i need to put them inside commands ?
like @on_button_click
Ah
Well there is nothing like that
But you can implement something like that on your own!
or something like that, cause when i restart my bot , my buttons don't work anymore, cause the command stopped
Do u know about botvars?
no
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
how can this help me ?
Wait I think there is a function like that
OK
!d discord.on_interaction
discord.on_interaction(interaction)```
Called when an interaction happened.
This currently happens due to slash command invocations or components being used.
Warning
This is a low level function that is not generally meant to be used. If you are working with components, consider using the callbacks associated with the [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") instead as it provides a nicer user experience.
New in version 2.0.
cool
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
i also found this
What lib r u using?
discord.py==2.0.1
BTW Catgal how is he gonna get the view object?
No function like that in dpy
okay
aha
thanks
Idk if it exists in discord py but in nextcord there's button callbacks
There are button callbacks in discord.py too lol
Every fork took button callbacks from dpy only
cool ! this worked after i restarted
Hey nice!
Using callback?
on interaction event probably
no , on_interaction
callbacks stops working after restarting i think
examples/views/persistent.py lines 39 to 45
async def setup_hook(self) -> None:
# Register the persistent view for listening here.
# Note that this does not send the view to any message.
# In order to do this you need to first send a message with the View, which is shown below.
# If you have the message_id you can also pass it as a keyword argument, but for this example
# we don't have one.
self.add_view(PersistentView())```
But then I am confused how does this even listen to events on an already sent view?
I mean, I don't think the bot can "see" the view that was sent before it restarted (as long as on_interaction isn't used)
hello
i had read your message
i want from bot to make an button on itself message when sent , and then , that bot take an action on that
When user presses a button, gateway dispatches event, bot receives it. If it finds a persistent component that has same custom id with payload's component, then it invokes its callback
@gilded gust for some reason the ping works as a prefix but the "ya" doesnt
prefix = ["ya","@clear monolith"]
@client.event
async def on_ready():
print("We have logged in as {0.user}".format(client))
@client.event
async def on_message(message):
message.content = message.content.lower()
cmd = message.content.split(' ')
if message.author == client.user or message.author.bot or cmd[0] not in prefix:
return
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
Is message_content intent enabled
!d discord.Intents.message_content
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
β’ The message was sent by the client
β’ The message was sent in direct messages
β’ The message mentions the client
This applies to the following events...
Also just use discord.ext.commands.Bot if you want to create text commands
it turns out it was not enabled, but i just assumed it was because the bot works fine when i use the ping
and it still doesn't work.
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Messages containing bot's ping don't need message_content intent to access content that's why
import os
import discord
import random
import cards
from keep_alive import keep_alive
from discord.embeds import Embed
intents = discord.Intents.default()
client = discord.Client(intents=intents)
oh... well then
i need to remodel all my code then
You only need to do commands properly that's it
Why flip table
because this looks like it takes a long time
will this work?
client = commands.Bot(command_prefix=["ya","@clear monolith"], intents=intents)
- Inconsistent variable naming, instance of
Botshould be calledbot, notclient - Instead of parsing bot's mentions as prefix, use
commands.when_mentioned_or
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
this really is going to take a long time
Why do you think so
i dont know how to use def
Understandable
You need functional programming and OOP knowledge
So I suggest taking python courses
Discord bot shouldn't really be one your first few projects
3 months of my life just to make this bot do something simple
^
what can i say. i feel like a pro when something works
Lmao
You can learn that stuff in a short period of time then practice on bot
That pro feeling will weeks to actually happen ngl
Everyone does
indeed. my motivation will die very quickly
Literally me
Rather 1 month of python learning and practice will make you much better
Learning basics of functional programming and OOP can be done within one day
Then pure practice and extending knowledge
Async programming too
you will go super-Sayan when you learn OOP and how to use classes trust me
Async programming can be learned from a discord bot
me who is coding bots that do things only cus i know how to use if statements
and lists
That's already cool but yeah functional programming and OOP are required
i aslo know how to use while loops
That's a good start :-)
watch me die of depression before i do that
books and yt videos are so hard to follow for me
but bad ending sedly
Examples 
stepik
me who is poor
There are free courses bru
Most of python courses are free
;-;
And personally I learned python from a book at like 10 years, then re-learned it on sololearn and then years of practice and docs reading
you are a pro
where can you host python scripts to run 24/7 for example i need my loop to run forever?
on your pc
VPS
no
what the
10 years + extra 5 years
Depends what kind of loop
Also try finding simpler projects to work on that don't involve complicated external libraries. Find ways to incorporate concepts into these projects that you're not very familiar with, so as to get some good Python practise going.
How the heck did you count that
lol
its a loop with discord requests
dang
mind tutoring me a little?
No I suck. :-)
I mean when I was 10 my brain was too small to understand OOP
ahh i fould a video over a year ago, telling a best github project to learn whole python π
TF U STARTED FROM 10???????
@vale wing the pro
mind tutoring me?
so
Yes lol
me who started a few months ago
REAL GIGA AGAIN FOUND
And I barely understood functions then got completely stuck on OOP
Because I didn't know english well that age
;-;
|| ||
||\\\\\\||
_ _
Btw that book that was my entrypoint to python programming was like "omg python 3 is out but it's bad, use python 2 π€"
i forgor how to do that lmao
Why don't we have reaction perms in this channel but other topic chats do
epic book
message can get spammed
u can also see other topics doesnt have channel cooldown but this channel has
xd
sed
I am not a programming teacher sorry lol, I can give you resources tho
Programming is best to be learned by oneself imo
"resources"
this is why im bad at life. i suck at learning in general
u will get more interest when u will complete some small projects
like printing hello world :)
hi
halo
i need examples/explanation how to connect to discord websocket using aiohttp, i don't understand websockets a lot
im very motivated to go straight to my bot than to do something small
then u will get stucked very bad xd
create some big game with only python and get motivated π
ash
"I have made a discord bot but the only catch would be that I don't know how it works"
seems cooler to say right
spook
y >:(
sorry I had to go
There's surely a way of getting information suitable for you
;-;
typing on phone is hard, not my fault
....... 70 wpm
indeed
I was on laptop lmao
........ oh hunter did 70 wpm on phone i forgor
if you're gonna keep up with that attitude for learning things, you'll never make it to the top
Hunnie Bunnie's like a God
He chats on instagram 14 hours a day what do you expect
i need a pro to take me step by step and doesnt give me too much info at once. books and readable sources explain so much that idk what im supposed to do. yt videos explain nothing and i just end up copying and pasting
books dont do that
demn
step by step πΈ
the only thing is he doesnt use instagram
what tf is this plot twist xd
darn it all i want in to add "ya" as a prefix
screw the prefix then
ill learn it when i make my other bot
for now, ill just use the ping
this
Why not use ready wrapper
because no
Connecting to websocket is very easy
examples
And yeah make sure to read this too https://discord.com/developers/docs/topics/gateway
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
if you want a tried-and-true example of connecting to discord's websocket with aiohttp, look at discord.py's source code and follow the method calls used by their DiscordWebSocket class
https://github.com/Rapptz/discord.py/blob/master/discord/client.py#L591-L597
discord/client.py lines 591 to 597
async def connect(self, *, reconnect: bool = True) -> None:
"""|coro|
Creates a websocket connection and lets the websocket listen
to messages from Discord. This is a loop that runs the entire
event system and miscellaneous aspects of the library. Control
is not resumed until the WebSocket connection is terminated.```
k
hey guys
hey ;-;
i actually chatgpt'd it
πΏ
Does your profile contain green goblin? Xd
yes it does.
Cool
hi
button_view = ui.View()
for i in range(len(self.submissions)):
# add dynamic number of buttons to view
button_view.add_item((ui.Button(label=f"Button #{i+1}", style=ButtonStyle.primary, custom_id=f"{i+1}")))
await interaction.channel.send(
embed=await MessageUtils.embed_message("message description example"), view=button_view
)
I have this code that adds a dynamic number of buttons to a message labeled "Button #X" where x is a number.
What can I do now to:
- for the next 60 seconds:
- allow all members to click the button once, but disable it only for that member after clicking
- see which button is clicked / how many times


