#discord-bots
1 messages Β· Page 805 of 1
@sick birch can i get some help with cogs now? ive got the file setup and loaded in but it doesnt seem to be recognizing commands
Is it possible to use variable in different files but in same folder?
if before.vanity_invite != after.vanity_invite:
await after.ban(i.user, reason="Anti-Nuke: Changing Guild Vanity")
try:
if str(i.guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**GUILD LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{i.user}`\nID: `{i.user.id}`\nPing: {i.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member changed the guild name!\n\n**__BEFORE__**\n\nGuild Vanity: `{before.vanity_invite}`\nGuild ID: `{before.id}`\n\n**__AFTER__**\n\nGuild Vanity: `{after.vanity_invite}`\nGuild ID: `{before.id}`\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Guild vanity has been restored", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
await after.edit(name=before.vanity_invite)
why is the guild vanity not editing back to the before vanity invite ?
Sure, how's the file look?
top is commands file, middle is bot.py file and bottom is the error message
im trying to host my bot using railway
and i cant seem to find the procfile
does anybody know how to get it
how to fix No module named 'discord_buttons_plugin'
is it installed?
Commands should be indented so theyβre in the class
Also donβt name ur commands on_message
ah, that fixed it. i also adjusted the names off of on_message cause i wasnt sure if that was the issue. thanks for the help
how to fix No module named 'discord_buttons_plugin'
do you have it imported?
obviously if im trying to figure out " how to fix No module named 'discord_buttons_plugin' "
@commands.Cog.listener()
async def on_guild_update(self, before, after):
async for i in before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.guild_update):
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(i.guild.id)]
channel_id = channel_config[0]
except:
pass
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(i.guild.id)]:
return
if before.vanity_invite != after.vanity_invite:
await after.ban(i.user, reason="Anti-Nuke: Changing Guild Vanity")
try:
if str(i.guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**GUILD LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{i.user}`\nID: `{i.user.id}`\nPing: {i.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member changed the guild name!\n\n**__BEFORE__**\n\nGuild Vanity: `{before.vanity_invite}`\nGuild ID: `{before.id}`\n\n**__AFTER__**\n\nGuild Vanity: `{after.vanity_invite}`\nGuild ID: `{before.id}`\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Guild vanity has been restored", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
await after.edit(vanity_code=before.vanity_invite)
why is the guild vanity invite not changing back to the before vanity invite?
atleast this is what the docs say
discord developer portal. if you somehow have it setup differently im not sure
you just open it in the web browser and then go over to the application and down to your bot
wdym?
where do i find the procfile
under bot, within the specific application
!?!?!
idk.
oh procfile. not profile
fuck me, i dont know what the procfile is. whats it used for or why do you need it?
quick google search sounds like the procfile is a file you make with a specific command to tell railway what to run
does your video tutorial say anything about how to make/get it
guessing not if your asking here
yes but it doesnt work
its supposed to take me to the file
or create the file or whatever
but it doesnt do anything
Using Python-decouple to use settings.ini as a token file, I get this:
~/artemis-mk2 $ python3 main.py
Traceback (most recent call last):
File "/storage/emulated/0/coding/python/artemis-mk2/main.py", line 6, in <module>
token = config('token')
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/decouple.py", line 243, in __call__
return self.config(*args, **kwargs)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/decouple.py", line 105, in __call__
return self.get(*args, **kwargs)
File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/decouple.py", line 90, in get
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
decouple.UndefinedValueError: token not found. Declare it as envvar or define a default value.
What do I do?
import disnake
from disnake.ext import commands
import os
from decouple import config
token = config('token')
bot = commands.Bot()
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}.")
bot.run(token)
That's main.py
does it look for settings.ini or config.ini
r u talking to me
that was towards player, im still looking for yours
k thanks
By default it's meant to look for that
do token=token with no spaces betweent hem
im also unsure if it requires "token" to be all uppercase
can i get some help with my event pls?
i lost my brain doing that lol
without the massive code dump yet what are you trying to accomplish and what is the end result so i have a bit of context
i am trying to get back the guild vanity url
Here
It was .htmltry because kryptonik fucked the link up accidentally
You didn't put a space after the link
ah
@neat tartan
ok so lemme tell u what it should do
get back as in just pull the guild vanity in general or get back as in retrieve what it was before it was changed?
so in this code everything works right except 1 thing the vanity url is not getting edited back to the before vanity url
the only thing that is happening in the code is that the member gets banned
and if logs are enabled logs will send too
before the bot changes the url save the current vanity url to a variable that way it stores it. then let it do the changes and to retrieve the old one back just call the variable you saved it to before the change
railway uses heroku to host be default from what i read
but not the bot is changing it
a "non trusted" member
people that are not whitelisted in the guild
anywhere the code is
ong my brain
both?
i dont think there is a way to pull a previous one. the best it could do is just grab the current vanity and hold onto it. if it is then changed the bot can compare them and reassign the presaved vanity
if you add it in vsc and then upload it to something like github the file would go with it and end up in both locations
im so confused
you could store a vanity whenever it changes (loop maybe?) in a database or such
ive never done this before
<bound method Guild.vanity_invite of <Guild id=924065171448692778 name='rares' shard_id=0 chunked=False member_count=340>>
oh there's a name atr
just add it to your vsc because anywhere you go to deploy the code it will follow it
have you ever hosted with railway?
that would be the closest to having a history but afaik discord doesnt keep a history of previous names, vanities, etc
nope, ive just hosted everything myself for the time being. id likely end up using some other hosting platform instead. but for all purposes i havent done anything hosted related
im getting confused
so
ong im lost
i cant be bothered doing this
wait name is the guild name
i would 100% say do not do this
why not
replit is pretty bad
@sick birch
so how can i get the before vanity code and the after vanity code?
AWS has a free tier
discord natively won't allow you to i don't think
is it 24/7?
course
i need help 
750 free hours per month on t3.micro instance
im getting confused
if this is intended for post damage cleanup you cant
huh?
sounds good
i figured that was the case. damage as in harmful changes to the discord after a nuking.
he still need help?
how can i make this work?
β οΈβ οΈβ οΈπ
https://discordpy.readthedocs.io/en/stable/api.html#discord.on_guild_update this is the right one
though i'm not sure how you can test since you'd need to change the vanity
Spooky I would help u cus i been did an anti-vanity like 9 months ago but na 
you too sensitive
if the vanity url has been changed BEFORE your bot is on the server you CANNOT grab the before vanity url. if your bot is on the server before the nuking and is supposed to prevent it the best thing it can do is grab the current vanity url to act as the before
brain fucking
its not that hard
depends how u tryna do it
yes u can
your dumb
π
i was pretty sure discord didnt hold onto that info thus making it inaccessible
so i just found out that
it does
before.vanity_invite this is totally not the code
just going on a hunch here but maybe on_guild_update's before and after have it
of the vanity

that's not lol
@sick birch
Pretty sure ur code is still wrong
I dont want to add mine?

dude i said
dude r u dumb?
ion believe u that u got a anti url now
that's not the name lol
that checks if the change was made for the url
it won't get the code
$15 for my code
<bound method Guild.vanity_invite of <Guild id=924065171448692778 name='rares' shard_id=0 chunked=False member_count=340>>

π
?

alright guys let's keep it on topic
i dont want to add mine
It just depends on the nuker ur ping and response time to guild audits

LMFAO
im trying to sign up and its making me use one @sick birch

or do i not have to sign up
hm, don't think you have a choice since they will start billing you if you go over the 750 hours
how is it possible to reach over 750 hours a month
its also likely a security measure on their part to make sure they will get the money if you choose to go to a paid version
multiple instances
send support server for spooky
Hey im getting this error for my command:
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/ubuntu/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'read'
@commands.command(usage="`tp!se emote`", aliases=["stealemote", "se", "steale"])
@commands.guild_only()
@commands.cooldown(rate=1, per=4.5, type=commands.BucketType.user)
@permissions.has_permissions(manage_emojis=True, manage_guild=True)
@commands.bot_has_permissions(embed_links=True, manage_emojis=True)
async def steal_emote(self, ctx, emote: discord.PartialEmoji):
"""Clones any emote to the current server"""
await ctx.guild.create_custom_emoji(
name=emote.name,
image=await emote.url.read(),
reason=f"{ctx.author} used steal_emote",
)
await ctx.send(f"I successfully cloned {emote.name} to {ctx.guild.name}!")```
this was working just fine like a few weeks ago and suddenly this is the error i get, i dont understand.
im using dpy 2.0
yeah you should consider purchasing one anyway since i would say AWS is one of the best hosts, it's used by a lot of major companies
Send support server @dry kelp
you can run multiple instances, and it's cumulative
sent in your dms
dude i am not having issues with the check
i am having issues getting the name
does it have a atr or smth?
if before.vanity_invite != after.vanity_invite: this part is already checking if a change was made to the url
which runs right after
the member will get banned
it stops before changing it back
cuz idk how to get the code
so does it have a certain atr?
like
after.vanity_invite.url
after.vanity_invite.code
please finish your sentence before you press enter lmao
no
ok
Okay and what have you done to try to accomplish this?
Are you storing the invite and then waiting for it to change?
Yes, if the vanity URL before != vanity URL after, ban user, change vanity back
or change vanity back and then ban
exactly how to i get the before url code
I would take priority over the vanity
that's my issue
Well
I guess you could append the invite then use a on_guild_update and go from there?
right so append the invite to store it and then wait for it to change, or save it in some json file then wait for it to change
So you can store the invite
Im pretty sure you cant
since its not explicitly stated that you can in the way you're trying
i thought this too but apparently you can and i got called dumb for thinking it
has it been proven that you can?
i didn't call u dumb
you didnt. federal did
@commands.Cog.listener(name="on_guild_update")
async def check_vanity(self, before, after):
code lol```
idk how he even got in the discussion
@commands.Cog.listener()
async def on_guild_update(self, before, after):
async for i in before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.guild_update):
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(i.guild.id)]
channel_id = channel_config[0]
except:
pass
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(i.guild.id)]:
return
if before.vanity_invite != after.vanity_invite:
await after.ban(i.user, reason="Anti-Nuke: Changing Guild Vanity")
try:
if str(i.guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**GUILD LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{i.user}`\nID: `{i.user.id}`\nPing: {i.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member changed the guild name!\n\n**__BEFORE__**\n\nGuild Vanity: `{before.vanity_code}`\nGuild ID: `{before.id}`\n\n**__AFTER__**\n\nGuild Vanity: `{after.vanity_code}`\nGuild ID: `{before.id}`\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Guild vanity has been restored", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
await after.edit(vanity_code=before.vanity_invite)
current code i got
ik this is wrong
i was testing
yes that thanks
If the vanity changes you will have to change it back using the before vanity
can i get some help with my issue btw
this is if you want to change the vanity
which you want to do yes?
if it changes by another user
yeah so you need to edit the vanity using the before vanity_url
by that i mean pass it into guild.edit()
await guild.edit()
how do i do buttons in python
after is the guild
let's trade codes
can i get some help with this
u got a help menu with python buttons?
yep
that actually work
k..
yep
do i pass it inside the edit?
vanity_code=before_url
@sick birch
that will get the entire url
but it won't change
that makes no sense tho
it gets in what the url changed
not the before one
are both before and after the same vanity URL?
looks like it
I suppose that makes sense
It's a coroutine, so I'm assuming it's not a cached property
mhm
how do ig et the last 10 messages of a channel
u gotta save them into a database
..
how do i do that WITHOUT a database?
i assume that u can't
why not
pretty sure the bot cannot read the last 10 messages
how?
why not dude
why don't u just create a json?
and?
u can't that's what im sayin
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
There's no point
that gets the first ones
u can set a limit
You want to get the first 10 messages?
So the most recent ones?
i recommend using a database
yeh
much easire
Yeah, just use history
easier*
It'll go from most recent -> least recent
well i tried that but it gave me the first ones
Did you pass in limit=None?
limit=10
How many messages were in the channel?
^^
Using a databases with messages? I thought discord.py models were only semi-serialisable at best
20ish
And your messages would have a high chance of being outdated
Database is not a right choice if you want to get the recent 10 messages
There's no point in storing the last 10 messages in a database when you can just use a built in method for it
thats what im saying
i prefer using database

All very good points
@quasi stag can we see your code? Something's off if it's giving you the first 10 messages
Don't think we can accomplish this without doing something clever, discord.py doesn't provide an easy way to do so
Off the top of my head, maybe a loop that runs every minute or so and checks if the vanity changes
async for toadd in message.channel.history(limit=10):
if toadd.author == message.author.bot:
strbuilder = strbuilder + "\nBen: " + toadd.content
else:
if toadd.author.nick:
strbuilder = strbuilder + "\n" + toadd.author.nick + ": " + toadd.content
else:
strbuilder = strbuilder + "\n" + toadd.author.name + ": " + toadd.content
i assume that there's a way to do it without doing that
also, i want the bot to read from bottom to top
You should be able to just create a listener for the guild_update event
so like, recent -> old
Yeah, history should do that by default
are u talkin to me?
Yes
We've tried that, but it doesn't seem like the vanity is cached
Store vanity on startup as a bot var
I'm pretty sure you'd know what your vanity url is anyways, you can hardcode that
Hmm yeah I suppose you could do that
Otherwise fetch it
@commands.Cog.listener()
async def on_guild_update(self, before, after):
async for i in before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.guild_update):
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(i.guild.id)]
channel_id = channel_config[0]
except:
pass
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(i.guild.id)]:
return
before_url = await before.vanity_invite()
if before.vanity_invite != after.vanity_invite:
await after.ban(i.user, reason="Anti-Nuke: Changing Guild Vanity")
try:
if str(i.guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**GUILD LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{i.user}`\nID: `{i.user.id}`\nPing: {i.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member changed the guild name!\n\n**__BEFORE__**\n\nGuild Vanity: `{before_url}`\nGuild ID: `{before.id}`\n\n**__AFTER__**\n\nGuild Vanity: `{before_url}`\nGuild ID: `{before.id}`\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Guild vanity has been restored", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
await after.edit(vanity_code=before_url)
current code
yikes
Yep....
that is a lot
Yeah try andy's idea, store your vanity as a bot var on startup
Is there any reason you look through the audit logs?
yeah
The only thing you seem to be checking is for a vanity url change
There is no point in a API call here
that's the right thing
You can just check the vanity of after and before
huh
they're both the same that's the issue
are u talking about this?
the only way to get the vanity through discord.Guild is through a await before.vanity_invite()
which makes an API call and seems to return the current vanity rather than before/after
this is needed because on_guild_update can trigger multiple things
Ok, and to solve that like I said earlier, just set a variable before hand or hardcode it in. I'm sure you'd know what vanity url you have
is made for multiple guilds
How can I get the ID of a member I mentioned in the chat?
ex: in chat I write "get member id @", and the bot gets and prints his ID?
^ yeah use a bot var and store or hardcode your vanity. if it changes, revert it back & ban the user
Yea, but it seems like the only thing your checking here is the vanity url, so you can check if it changes
Otherwise if it doesn't do nothing
No need for a pointless audit log call to check for something you already know can be happening without a API call
perhaps a database of vanities? though that seems kind of like data harvesting
huh
i need to call it so i can ban the user
Oh they want to find out who changed the vanity
the user that made the change
Ah that makes more sense now
Yeah that's a bit more tricky
Ok, so to get back on topic just store the vanity url to the guild id beforehand
Simple key-value pair in your database, boom bop done
jesus christ
Still feels like data harvesting doesn't it
yeah but storing the vanities of all guilds in a database
it's made for a good purpose
π€
I suppose go for it but make sure your users know that you are storing their vanities
well there's no point in protecting a vanity if they don't have a vanity
The user would use some config command to set it up I presume, so that would basically be them giving consent I think
But I'm no lawyer so
i can set that up
i will once i find out how to fix this shit
i still have no idea tbh
with open(path, 'wb') as f:
f.write(...)
so ur telling me to do this?
@pliant gulch
why a regular file
use something like postgresql with a 2 column table, guild ID and URL
sqlite3?
Could be a legal issue as well, some cases and depends where you are, you are legally required to securely store your data from users
yeah storing in a text file is quite the opposite of security
@angel.event
async def on_ready():
db = sqlite3.connect('database.sqlite3')
cursor = db.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS welcome(
"guild_id" INTEGER,
"channel_id" INTEGER,
"msg" TEXT DEFAULT 'Hey $user_mention',
"title" TEXT DEFAULT 'Welcome to $server',
"color" TEXT DEFAULT '#000000',
"footer" TEXT DEFAULT 'Spooky Welcomer',
"embed" INTEGER DEFAULT 0,
"ping" INTEGER DEFAULT 0,
"autodel" INTEGER DEFAULT 0,
PRIMARY KEY("guild_id")
)
''')
db2 = sqlite3.connect('anti_vanity.sqlite3')
cursor2 = db2.cursor()
cursor2.execute('''
CREATE TABLE IF NOT EXISTS vanity(
"guild_id" INTEGER,
)
''')
don't mind the 1st part
is another database
sqlite3 is blocking
use either asqlite or aiosqlite
imma just use this π
it's blocking though
fuck it
if you say so
well i never write sql these days so you're kind of on your own for the sql statements
raw sql queries are overrated
alright just make sure the table has 2 columns, guild ID and vanity url
right now it only seems like it has a guild ID
prisma orm π
yep
cursor2.execute('''
CREATE TABLE IF NOT EXISTS welcome(
"guild_id" INTEGER,
"vanity_url" INTEGER
)
''')
there you are
cursor2.execute('''
CREATE TABLE IF NOT EXISTS vanity(
"guild_id" INTEGER,
"vanity_url" INTEGER
)
''')
now you should be able to just put stuff into those tables (don't ask me how)
"hOwWw"
nah jk
all ik ```py
with sqlite3.connect('.anti_vanity.sqlite3') as db:
db.row_factory = sqlite3.Row
cursor = db.cursor()
@sick birch
yeah should work
yeah it should
and now how do i store it?
like
how do i get the before url doing this
still reached the same issue 
@sick birch
query = "SELECT * FROM vanity WHERE guild_id = ?"
val = (before.id)
with sqlite3.connect('.anti_vanity.sqlite3') as db:
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute(query, val)
store every guild's vanity in there at startup
idk if it does
probably a loop with wait_until_ready
this will store only when it get changed
@commands.Cog.listener()
async def on_guild_update(self, before, after):
async for i in before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.guild_update):
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(i.guild.id)]
channel_id = channel_config[0]
except:
pass
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(i.guild.id)]:
return
query = "SELECT * FROM vanity WHERE guild_id = ?"
val = (before.id)
with sqlite3.connect('.anti_vanity.sqlite3') as db:
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute(query, val)
before_url = await before.vanity_invite()
if before.vanity_invite != after.vanity_invite:
await after.ban(i.user, reason="Anti-Nuke: Changing Guild Vanity")
try:
if str(i.guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**GUILD LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{i.user}`\nID: `{i.user.id}`\nPing: {i.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member changed the guild name!\n\n**__BEFORE__**\n\nGuild Vanity: `{before_url}`\nGuild ID: `{before.id}`\n\n**__AFTER__**\n\nGuild Vanity: `{before_url}`\nGuild ID: `{before.id}`\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Guild vanity has been restored", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
await after.edit(vanity_code=before_url)
oh so ur saying
to fetch all the guild ids
in that on_ready event?
@sick birch
then it should do the job
no it won't, it's bad practice and will only get your bot disconnected from the websocket
using a database is never a bad idea
i meant sqlite3
postgres is a robust database and one of the most popular
just sayin that idk how to use those so i will just fuck ur brain
i don't either in python, the only way i've done it is have an Express.js server running prisma that interacts with the postgresql database, and I can send API calls to that server using aiohttp and interact with the database
That way you don't have to deal with the python database connectors and writing the nasty sql queries
so
back to my main question
since the beginning
how can i get the before url without using database
i am pretty sure that i don't have to sort all of this
well you could store all the vanities in a text file or whatever but it's incredibly insecure and difficult to work with
that would be better because nobody can access my root or anything
still a pretty bad idea when you consider how you would have to work with it in python
makes sense but let's try this
it's gonna turn into spaghetti code really fast and we won't be able to tell what's what
π
makes sense
another question
does discord have a api?
with all the urls/guild ids
how else would discord.py work
so there is
of course
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
let me take a look

no, it get the vanity at the time of sending the request
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(str(error))
else:
with open("runtime_errors.txt", "a") as f:
# Error on this line: SyntaxError: invalid syntax
f.write(f"{t.strftime("%m/%d/%Y, %I:%M")} || {str(error)}\n")```
make sure it's indented properly, the command and the succeeding line don't seem to be on the same indent level
this is it
Yes, you'd need to store the vanities of each guild on startup
make sure they're on the same line, python doesn't like that when you split a line halfway like that
the vanity url code?
YE
yes
ye*
you would have to store it
and how do i get it
on startup, go through every guild the bot is in and await guild.vanity_url(), then store that
wym by on "startup"
when the bot turns online
on_ready?
from the docs:
from discord.ext import tasks, commands
class MyCog(commands.Cog):
def __init__(self, bot):
self.index = 0
self.bot = bot
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
@printer.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
yes
didn't u say that is not alr doing things on_ready event?
looks like you're not closing that f string
i did
and then why am i doing it?
you shouldn't do anything except maybe printing in on_ready()
use something like this
the parenthesis, braces and quotation match up
should i use it in the same file?
i rlly dont know why
doesn't matter
is not working
the f string isn't closed properly
r u talkin to me?
yes
i need an extra quote?
Yes, and replace the double quotes around the strftime format to single quotes
import discord
from discord.ext import commands
import json
import datetime
import pathlib
import sqlite3
from discord.ext import tasks, commands
whitelist_path = pathlib.Path(__file__).parent / "whitelisted.json"
prefix_path = pathlib.Path(__file__).parent.parent / "prefix" / "prefixes.json"
channel_path = pathlib.Path(__file__).parent / "Logs.json"
black1 = 0
black2 = 0
black3 = 0
class MyCog(commands.Cog):
def __init__(self, bot):
self.index = 0
self.bot = bot
self.printer.start()
def cog_unload(self):
self.printer.cancel()
@tasks.loop(seconds=5.0)
async def printer(self):
print(self.index)
self.index += 1
@printer.before_loop
async def before_printer(self):
print('waiting...')
await self.bot.wait_until_ready()
class AntiVanity(commands.Cog):
def __init__(self, angel):
self.angel = angel
@commands.Cog.listener()
async def on_guild_update(self, before, after):
async for i in before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 1), action=discord.AuditLogAction.guild_update):
with open(channel_path, "r") as f:
config_channel = json.load(f)
try:
channel_config = config_channel[str(i.guild.id)]
channel_id = channel_config[0]
except:
pass
with open(whitelist_path, "r") as f:
whitelisted = json.load(f)
if str(i.user.id) in whitelisted[str(i.guild.id)]:
return
before_url = await before.vanity_invite()
if before.vanity_invite != after.vanity_invite:
await after.ban(i.user, reason="Anti-Nuke: Changing Guild Vanity")
try:
if str(i.guild.id) in config_channel:
log_channel = self.angel.get_channel(int(channel_id))
embed = discord.Embed(title=" Anti-Nuke ", description=f"**GUILD LOGS**\n\n**__NON TRUSTED MEMBER__**\n\nMember: `{i.user}`\nID: `{i.user.id}`\nPing: {i.user.mention}\n\n**__ABOUT__**\n\nNon-Trusted member changed the guild name!\n\n**__BEFORE__**\n\nGuild Vanity: `{before_url}`\nGuild ID: `{before.id}`\n\n**__AFTER__**\n\nGuild Vanity: `{before_url}`\nGuild ID: `{before.id}`\n\n**__ACTIONS__**\n\n Non-Trusted member has been banned out of the server!\n Guild vanity has been restored", color=discord.Color.from_rgb(black1, black2, black3))
await log_channel.send(embed=embed)
except:
pass
await after.edit(vanity_code=before_url)
def setup(angel):
angel.add_cog(AntiVanity(angel))
lemme make a myst
still
Can you post the text here? hard to see it
with open("runtime_errors.txt", "a") as f:
f.write(f"{t.strftime('%m/%d/%Y, %I:%M')} || {str(error)}\n")```
hello from rasberry pi, i have taken my code and put it in the same app on rasberry pi, but it says that discord is not accsesed when i do import discord, so do i need to separetly sudo install discord.py?
im recording the error aswell
yes that part is fine, which is why i left it out
from where do i import discord, is there a separate thing i need to install?
AttributeError: 'list' object has no attribute 'user' any help?
You'd use pip for that, not apt
this is rasberry pi os
list has no atr for user
simple
isnt pip for win or am i tripping
pip is for python
ik but
ohh
send code
which one of them?
thank you robin
Remove the f string, itβll make things much easier
no u gone steal and run off
im on mobile so i cant rlly look at da code but ik smth wrong , and that is definitely a lie
so now how do i concatenate the error and the time?
i tried this and it didnt work python with open("runtime_errors.txt", "a") as f: f.write(t.strftime('%m/%d/%Y, %I:%M') + " || " + str(error))
that works
@sick birch
so federal sent me a code for the anti vanity
but is like
kinda fucked up
pretty sure we can debug it
@commands.Cog.listener()
async def on_guild_update(self, before, after):
reason = "Anti-Nuke | Updating Vanity URL"
i = await before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.guild_update).flatten()
whitelisted = db.find_one({ "guild_id": after.id })['whitelisted-users']
if i.user.id in whitelisted:
return
rolelisted = db.find_one({ "guild_id": after.id })['whitelisted-roles']
if i.user.id in rolelisted:
return
if self.bot.user.id == i.user.id:
return
like i said that's very fucked up π
you werent kidding
@sick birch also what do i do after i used that?
it fixed
do i store the guild id?
looks like weird code not gonna lie
repl was just going stupid
yeah store every guild ID and their corresponding vanity url
thx anyway
what does this mean
Hello π
**How do I make a discord bot check connections a user has? **Such as reddit or xbox. I know it has something to do with oauth2 and i have to authenticate smth, but I dont quite get what Im supossed to do.
wait
oh shit delete that rq
it has bots token
ok we are good
BRO I WILL but how do i fix the prblem
it worked fine on windows
this rasberry pi stuff is sorta new for me
it shouldnt be on desktop
do i change the file code to somewhere else?
Regenerate your token anyway.
[Errno 2] No such file or directory
will do
can't open file '/home/pi/Desktop/TOKEN =
token has been regenned
Guys how do i use the connections scope with my python script?
on_member_update and on_guild_update are both giving errors? 
Traceback (most recent call last):
File "/home/pi/Downloads/riot bot 5, no way this works.py", line 13, in <module>
from asyncio.windows_events import INFINITE
File "/usr/lib/python3.7/asyncio/windows_events.py", line 3, in <module>
import _overlapped
ModuleNotFoundError: No module named '_overlapped'
from contextvars import Context
from multiprocessing import context
from tokenize import Token
from types import MemberDescriptorType
from chardet import detect
import discord
import random
import sys
from discord import Embed
intents = discord.Intents.all()
client = discord.Client(intents=intents)
from asyncio.windows_events import INFINITE
from cProfile import run
from discord.ext import commands
from urllib import response
from asyncore import loop
from timeit import repeat
import asyncio
from discord import Member
line 2-20
i think it overlaps?
either that or i have the same thing twice
You'll have to use OAuth, with the connections scope. And this won't be possible via using the library - you will have to get the requests yourself.
Ever heard of pep8?
no I have not good sir
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
β’ PEP 8 document
β’ Our PEP 8 song! :notes:
1st one is a keyerror
so pass that
i am trying to make a anti url
but my brain ain't workin
Ok so ya know the code I tried to make earlier today with the sending of. Gif if a phrase was said? It does not work on phone, is that a code problem or discord problem

@bot.listen()
async def on_message(message: discord.Message):
if message.author.bot: return
for i in lfg:
if message.channel.category.id == 928088528754192446:
return
if i in message.content:
return await message.channel.send("https://media.discordapp.net/attachments/576923789359710217/933935463876669521/p2veyzf4iup.gif")
It shouldn't affect things, if you've just used an on_message event
it just doesnt work on mobile
You seem to be missing a double quote at the end
copy paste error
its there in code, i double checked
Is it a discord issue or code issue is what om@tryna know
What do you mean by "not working" though? The bot is not sending the link?
Yea
what url do i request it from?
If I were to say the phase lf4m which is one of the trigger words, it wonβt send the link, but on pc it does
also idk why but it does this when i try to accept connection scope alone
Integrate your service with Discord β whether it's a bot or a game or whatever your wildest imagination can come up with.
oh
@sick birch how would you pull a users message history? either through the search bar or just being able to straight pull it
Pls halp 
Are you looking for it in a guild, a specific channel, or DMs?
is @me a placeholder? /users/@me/connections @timid wagon
So all the channels of the guild then
like for @me do i put userid
@me is a representation for the current authorised user
E.g the user of the token
its just to grab previously sent messages to splice together
It is not a placeholder
Use print() under checks to see where the issue is. Maybe check if you're getting the content from mobile at all
okay so then uhhhhhhh, where do i specifiy which user im trying to get the connection from?
or do i use the access tokens?
You can use channel.history() in a loop to check all channels, and use a lambda function to filter them for a specific user
I'm not sure how it works with Oauth2
thats fine no problem
But with the regular restful API I can for sure say @me is for the current in-use token
is there way I can grab the list of people who accepted the token?
I assume requesting the endpoint using the access token will work though?
im sure there is ye?
Your question would be better answered at a server like DDevs - we're limited on users who've tried things with OAuth2 here.
yeah that's kinda what i meant
Try it out perhaps
Not sure what other token you'd use for Oauth2 other than the access token given
what url do i use to grab the people who have a token on said bot?
alright
thank you very much,
@timid wagon ahh i found some more info on what u were talking about
Yep
thanks mate
Sure. Try using Postman or Insomnia to test out those requests with your own headers - might help you while implementing them in code.
Alrighty
U wanna use the Discord API to access user info or smth?
!pypi pypresence use this
Yeah but they already helped me out
I got a sense for how to do it using oauth2
Just gotta do some testing and get it right
@maiden fable what does pyprescense do?
is there any documentation about channel.history()or even just history()?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destinationβs message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
Textchannel
fml, thanks
They wanna access user connections, so that package won't help
iirc it will
Shows custom rich presence on yr profile and can help u to authenticate with OAuth2
How is that related though 
And I thought RPC was deprecated
If type checking was done at runtime, it was have been nothing but errors
I guess I can add RPC support to rin
It is a very old example
Well the RPC docs says it's deprecated or something
instead of writing typing.Callable, callable was written without even importing it lmao
Oh, in private beta
Yea
Does this mean I can still use the API or...
Cause I'm sure if pypresence is there regular people can set custom RPC as well
Yea, but the problem is, u need the discord app
discord app as in the client?
Yea
I guess rin will get RPC support after all
The installed version
I still don't get how an RPC client will be able to get the user's connected accounts. It's not even documented
I tried it once, wasn't working since beta
Dude its not an RPC client
And I cba to look through the source code
Its a whole API wrapper
they have an authorise method that allows for scopes
Which then generate a access token I pressume?
Its just written as a RPC client, since that's what most of the people use it as, but it can also be used for authenticating
Yea
huh
@timid wagon
Look at this image he sent
PoV: He ignored it
well they need to update their docs
How
.....?
Makes sense to me, the wrapper is meant for RPC but they have a helper method for scopes
I saw it and assumed it was just referring to RPC
lmaoo
Its commented out, and yea. Comment colors suck on discord
So this means I can't add RPC support to rin yet π
Yes.
Why is RPC even in private beta !?!?!?!?
Fuck knows. Been like that since months
Most probably cz discord want to implement Message Intent first π€£
When I was adding the intents builder to rin they haven't even added the intent flag
So I just had a random gap in falgs
π ocd killing me
Rip
rin/models/builders/intents.py lines 141 to 143
DIRECT_MESSAGE_TYPING = 1 << 14
GUILD_SCHEDULED_EVENTS = 1 << 16```
Tf is this
What is <<
It's a bit shift operator
uhhhh
x << y
``` == shift x left by y bits
I still don't understand
If you want to understand it I suggest searching up bit shifting and bits, etc
Neat
π that's a whole thing that I cba to say here
Can you tell me. What features can I add in my bot and it wont lag if I have 1gb storage and 512 mb ram
Doesn't work like that
You cannot estimate that
WDYM
Can you tell me. What features can I add in my bot and it wont lag if I have 1gb storage and 512 mb ram
There's a lot of things other than your server's hardware, that you factor in for the bot's performance
The number of guilds its in, the amount of events its accessing, how you implement logging, and so on.
With discord bot's its mostly gonna be memory usage
And that's linear with amount of users/models it can see
As all of those get cached in-memory
Last I check, you could perhaps expect 100 users to be around 70mb??? I'm not sure it's been a while but I remember seeing some metrics
That depends on the member data although keep in mind, and this def changes with presence data
Can anyone tell me how much ram does a full working commands discord bot need if it is in 1k server
Why not test it yourself?
1k users is pretty specific
how can i get the channel id of the one mentioned?
so if i do !getchannel #discord-bots, that should give me the id of the channel
The channel ID.
u can just typehint the arg to discord.TextChannel, and then use this ^
isn't it called the bullshit operator?
oh ok
!d discord.abc.GuildChannel more efficient
class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.
The following implement this ABC...
80k members with 163 MB RAM
Messages and Members intent on
117 Guilds
I want to send a message to a channel that is different then the one it is getting sent to rn and keep it sending to the one it is getting send to rn how would i do that? like a log for each person who used the command?
Not to bad
Message cache size?
what
oh
get the channel object then send a message
you can make the cache bigger
example?
Default is 1000
Memory-usage is actually pretty low I guess, I wasn't expecting it to be that low for 80k members
@slate swan tf happened to the old wrapper
thx
π
does anything need to be changed for a cog?
prob a self added to the client
yep
died
seeeeshh
Hey is it ok if I make economy bot?
better than dpy's long method names ngl
Is 1gb and 512mb enough if bot is in 1k servers and it won't lag?
yeah sure
there are no errors it simply doesn't work
do you have intents on?
yes
!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 the Members and Presences intents, which are needed for events such as on_member 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.
I told you, you need to remove the .id from the fourth line
yeah i removed that
Yea, I was also shocked
Wait what? Same names?
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
yeah i have this
try to print the member
if nothing prints its your intents
if it does its what roie said
no intents lol
nope
intents=intents
Then why is it in the screenshot
Add this in the bot init
intents=intents
do py commands.Bot(intents=intents, ...)
ohh it's working now
lol
i missed that lol
Should I continue discord.py (v1) or start disnake?
disnake
disnake
Ouch thanks
Does dsnake have buttons and dropdown?
yes
yeah it does
Ouch nice
Is it similar to discord.py?
yes
disnake is fork of discord.py
just change the name space from discord to disnake for old features
so yes
with new ones its a bit different
You know... Use hikari if u can switch syntax or rin, right @pliant gulch?
π
Does it have py bot=False?
hikari?
Yea...
!pypi hikari
rin is coming nicely
A sane wrapper
Ou never heard of it
lel
Tho u should look into rin too
Not on PyPi the last time I checked π
Mmm for now I guess I will do disnake
And yea, Andy would be proud of u too