#discord-bots
1 messages Β· Page 1142 of 1
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
well try updating the library
Also @slate swan. Do you know how to define guild in the on_ready function? I would like to use the variables guild.name and guild.id
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
you would need atleast the ID to do this
pip install -U py-cord==2.0.0rc1
if that doesnt work, use git to install their master branch
That solved it thanks!
so like?
#test
@bot.command()
async def test(message):
user = message.author
role1 = discord.Guild.get_role(993231458846122014)
await user.add_roles(role1)
I appreciate your patience with meπ
message.guild.get_role
btw, its a Context object, not a Message, so you can call it context or ctx, not message.
this avoids confusion for both you, and the people who are trying to help you
i see, thank you and apologies if i've been 'difficult'π
in my bot, I'm trying to grab data from the cache but I do it too fast, how do I make it wait
await bot.wait_until_ready()```
guys I'm asking for a friend,
did they remove the ability to selfbots finally? thank god no more abusers
Yea...
when did they? and can i read the patch notes? my friend is really interested
not me pff never break tos
You can tell your friend to ask here instead of asking some other friend to ask here
:sus:
oh no thats bad tho
like eh why havent discord banned the WS API for user accs if discord for users on the web works with web requests?
Well you have things like changing presence, which is a gateway command
Also Iβm gonna assume itβs the same ordeal for stuff like receiving messages, as a websocket saves more bandwidth than using just web requests
am i sitting on a websocket connection rn then?
I think so, but to be fair I cannot see the source as Iβm just a regular user
Most chat apps now a day use websockets, thatβs pretty much the golden standard
So itβs very safe to say discord does too
Itβll be super ineffective to use web requests for receiving messages, etc
discord does use it for bots, i know that but when you post messages on the web discord it sends web requests, iirc
Yes, but receiving is my point
Itβll be βhardβ to know when to receive a message with just web requests
Thatβs when websockets come into play
Since they are bi-direction to discord and to the user
ah cuz discord is a client
Mhm
def check(message):
return message.channel == ctx.channel and message.author == ctx.author
link = await self.client.wait_for(event="message",check=check)
await request(item,value,link.content)```
anyone know why link.content might be empty? all other attributes work fine, but i cant get the content for some reason
Message content intents
!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...
My persistent view code is this```py
class PersistentView(View):
def init(self):
super().init(timeout=None)
self.add_item(AlphaDropdown(custom_id="persistent_dropdown"))
for link in links:
self.add_item(Button(label=link.label, url=link.url))
@button(label="I still need help!", style=ButtonStyle.blurple,, custom_id="Further-Support",, emoji="π©", row=3,)
async def green(self, interaction: Interaction, button: Button):
role = await interaction.guild.get_role(self.config.further_support_role)
if role is None:
log.error( f"Could not find role for further support with id: '{self.config.further_support_role}'")
return
try:
await interaction.author.add_role(role)
except HTTPException:
log.error( f"Could not add role for further support with id: '{self.config.further_support_role}' to user: '{interaction.author}' ('{interaction.author.id}')")
return
await interaction.response.send_message(f"You have been given the {role.mention} role to gain access to the further support channel.", ephemeral=True,)
Hi, how can I get the Moderator who banned a user in the on_member_ban event?
I tried this but it's kinda bugging when Raids happen and multiple Moderators are Banning more Users within a short period of time
@bot.event
async def on_member_ban(guild, member):
logs = await guild.audit_logs(limit=1, action=discord.AuditLogAction.ban).flatten()
logs = logs[0]
user = logs.user
if logs.target == member:
# Do some things...
That code should work as logs.user gets the user who banned the member. Are you saying that with multiple bans it starts to bug out?
Yes. Sometimes the server gets raided with like 50+ Bot Accounts and the moderators ban them very quickly
The bot should be as fast as them banning the bots but maybe it's reading the audit log to slow? I don't see a issue with the code.
It's just the asynchronous nature of things.
how would i make a website for managing a discord bot?
Hey everybody I'm new around here but have a question how do i pull in real time data with my bot. I am building an anti-scam bot. That reports scammers to the proper authorities but using the api to pull and post that data's challenging. Its an amazing project to have save people from being terrorized. Sorry if my grammar sucks lol
lol. no
they still exist
ik a website people use (not gonna say obv) but they still work just not how they use to be
sounds like you are
didnt see this lmao. i think (may be wrong) because i dont tinker with them their might be free ones but ik of one thats paid and quite good
i mean we all had to of use a self bot once before
can someone help me making a easy link button you can just add using await ctx.send like add the button there using rapptz or anything
ill pay
damn
dm me
!d discord.Guild.vanity_invite
await vanity_invite()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Returns the guildβs special vanity invite.
The guild must have `VANITY_URL` in [`features`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.features "discord.Guild.features").
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to use this as well.
is there a way to check if a message has a discord invite?
on_message event
Then check if the message contains "discordx. gg/"
yeah exactly
?
ok ty
and can I check if the invite sent is the invite to the server the message has been sent to?
I don't know if you can check what server the invite link is from
okok ty
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have the [`manage_guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_guild "discord.Permissions.manage_guild") permission to edit the guild.
Changed in version 1.4: The rules\_channel and public\_updates\_channel keyword-only parameters were added.
Changed in version 2.0: The discovery\_splash and community keyword-only parameters were added.
Changed in version 2.0: The newly updated guild is returned...
guild.vanity_invite() returns the vanity with the discord.gg is there a way to remove that and just get the vanity by itself?
strip it off?
just replace/strip discord.gg from the string
ahh forgot about strip() for a second
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix="@",help_command=None,intents=discord.Intents.all())
async def setup_hook(self):
async with aiosqlite.connect("prefixes.db") as self.connect:
async with self.connect.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER prefix TEXT)')
await self.connect.commit()
bot = botclass()
Guys where do I need to define the setup hook ?
sounds amazing
what kind of real time data are we talking about?
At this
you already defined it
nice cm logic
Oh k
it will run automatically now
Is code correct?
sql query is wrong, should have a comma in between of fields
Oh k
I gotta continue studying bye
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix="@",help_command=None,intents=discord.Intents.all())
async def setup_hook(self):
async with aiosqlite.connect("prefixes.db") as self.connect:
async with self.connect.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
Bye
yes
I'll do in class
from discord_webhook import DiscordWebhook, DiscordEmbed
webhook_enable = os.getenv("webhookVC_enabled")
webhookurl = os.getenv("webhook")
ping = os.getenv("webhook_ping")
if webhook_enable == "True":
webhook = DiscordWebhook(url=webhookurl, content=f"{ping}")
while True:
try:
scraper = cloudscraper.create_scraper()
r = scraper.get('https://rest-bf.blox.land/chat/history').json()
check = r['rain']
if check['active'] == True:
grabprize = str(check['prize'])[:-2]
prize = (format(int(grabprize),","))
host = check['host']
getduration = check['duration']
convert = (getduration/(1000*60))%60
duration = (int(convert))
waiting = (convert*60+10)
sent = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(int(time.time())))
print(f"Bloxflip Rain!\nRain amount: {prize} R$\nExpiration: {duration} minutes\nHost: {host}\nTimestamp: {sent}\n\n")
if webhook_enable == "True":
userid = requests.get(f"https://api.roblox.com/users/get-by-username?username={host}").json()['Id']
thumburl = (f"https://www.roblox.com/headshot-thumbnail/image?userId={userid}&height=50&width=50&format=png")
embed = DiscordEmbed(title=f"{host} is hosting a chat rain!", url="https://bloxflip.com", color=0xFFC800)
embed.add_embed_field(name="Rain Amount", value=f"{prize} R$")
embed.add_embed_field(name="Expiration", value=f"{duration} minutes")
embed.add_embed_field(name="Host", value=f"[{host}](https://www.roblox.com/users/{userid}/profile)")
embed.set_timestamp()
embed.set_thumbnail(url=thumburl)
webhook.add_embed(embed)
webhook.execute
webhook.remove_embed(0)
time.sleep(waiting)
elif check['active'] == False:
time.sleep(30)
except Exception as e:
print(e)
time.sleep(30)β
id = self.message.id
Is it correct?
It doesn't post the webhook and no errors either
Can I suggest one thing to you?
Ye
Use ```py
I did
To make it python code block
I'm on mobile so is tricky rn
It not looks
Me also on mobile
import cloudscraper, time, requests, os
from discord_webhook import DiscordWebhook, DiscordEmbed
webhook_enable = os.getenv("webhook_enabled")
webhookurl = os.getenv("webhook")
ping = os.getenv("webhook_ping")
if webhook_enable == "True":
webhook = DiscordWebhook(url=webhookurl, content=f"{ping}")
while True:
try:
scraper = cloudscraper.create_scraper()
r = scraper.get('https://rest-bf.blox.land/chat/history').json()
check = r['rain']
if check['active'] == True:
grabprize = str(check['prize'])[:-2]
prize = (format(int(grabprize),","))
host = check['host']
getduration = check['duration']
convert = (getduration/(1000*60))%60
duration = (int(convert))
waiting = (convert*60+10)
sent = time.strftime("%d/%m/%Y %H:%M:%S", time.localtime(int(time.time())))
print(f"Bloxflip Rain!\nRain amount: {prize} R$\nExpiration: {duration} minutes\nHost: {host}\nTimestamp: {sent}\n\n")
if webhook_enable == "True":
userid = requests.get(f"https://api.roblox.com/users/get-by-username?username={host}").json()['Id']
thumburl = (f"https://www.roblox.com/headshot-thumbnail/image?userId={userid}&height=50&width=50&format=png")
embed = DiscordEmbed(title=f"{host} is hosting a chat rain!", url="https://bloxflip.com", color=0xFFC800)
embed.add_embed_field(name="Rain Amount", value=f"{prize} R$")
embed.add_embed_field(name="Expiration", value=f"{duration} minutes")
embed.add_embed_field(name="Host", value=f"[{host}](https://www.roblox.com/users/{userid}/profile)")
embed.set_timestamp()
embed.set_thumbnail(url=thumburl)
webhook.add_embed(embed)
requests.post(webhook.execute)
webhook.remove_embed(0)
time.sleep(waiting)
elif check['active'] == False:
time.sleep(30)
except Exception as e:
print(e)
time.sleep(30)β
Fine now ? @robust fulcrum
Can you help with this
Me noob at python
@robust fulcrum From where are you if i could ask?
You dont need to answer the question if you dont want to
Place?
no country
India
Oh okay
why dont you use discord.py
also, what the issue?
N O
ew
better than using a discord_webhook library
ew
π₯ i'd rather use httpx
sleep
I'd use hikari π
ew
imagine using a library just to make POST requests
use requests π
I'd just use js in that case
requests bad bad
httpx best
no
is there a limit to how many choices i have in an autofill?
XMLHttpRequest better π
autofill as in? autocomplete or display choices?
depends on wym by autofill
cursed
autocomplete?
js β€οΈ
it should be autocomplete
you can have as many (but only 25 show up for suggestions)
yea autocomplete
there;s a limit of 25 suggestions in autocompletes
js users try to use 109 of them
so it displays 25 but i can always just input the rest?
like it shows the first 25 options
yep
it doesnt show up magically, you gotta provide a logic to your autocomplete for that.
what do you mean
a list comp generally
ye i have all my options in a list
what library are you using
im using pycord
imagine being so rude
async def autofill(ctx: discord.AutocompleteContext, choices):
return [auto for auto in choices]
i referred to that when i wrote the above function
it worked for something where i had 32 options but i just wanted to know if i had something like 300 it would still work
use [:25] to get the first 25 elements in the list then...
it would but u can show only 25
ik, thanks
yeah im ok with that, i just wanted to know if i did have it setup that if i started typing something out of the 25 then it would still work
i just didn't know if there was a limit for that part
mostly 25 is limit 25 button 25 select option 25 reactions
are buttons 5x5 grid?
basic python.
or can i have 2 rows of 10 or something
u cant select like that it depends on button size
you cant have more than 25 items in a view, a select menu is treated as 5items btw
np
discord is so obsessed with 25 limits
yeah, and next day see dank memer with 1000 buttons
ruder
Literal football field
indeed lmao
!d discord.User.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
So I would do
await ctx.user.send("this is a dm")
dming the author of the command?
yes
ok thanks
you have to pass in iterable to random.choice
ah okay is that all?
should prob try it first nvm
man literally entered iterable there ;-;
thought thats what they meant π
why
just have a random.choice on the 2 words and send the embed, theyre both the same, just pick the random word
since youre sending a file as well save it as a var
!e
import random
def coinflip():
print("Heads" if random.randint(0, 1) else "Tails")
for i in range(5):
coinflip()```
Love internet here
you can just have random.choice????
πΏ
Whats correct then
what's self.message?
In a class
Means how can I get guild I'd of message
message.guild.id dude
Oh k
You told to use same connection but it shows undefined
do you know how classes work?
How can I make it work?
Learning OOP before doing this would make things easier
(self, message)
I mean that cursor is being red line
But Ashley told to use same connection
u didnt even create a connection u used a context manager ;-;
^
show ur setup hook code
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix="@",help_command=None,intents=discord.Intents.all())
async def setup_hook(self):
async with aiosqlite.connect("prefixes.db") as self.connect:
async with self.connect.cursor() as cursor:
await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
async def get_prefix(self,message):
id = message.guild.id
await cursor.execute('')
Is there any defect in it?
async def setup_hook(self):
async with aiosqlite.connect("prefixes.db") as connect:
self.db = connect # <-- connection to db here
async with connect.cursor() as cursor:
self.cursor = cursor # <-- connection to db cursor here
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)') # <-- refer to cursor as self.cursor
await self.db.commit() # <-- refer to db as self.db
async def get_prefix(self,message):
id = message.guild.id
await self.cursor.execute('')
await self.db.commit()
this should give u a better idea
its discord.app_commands
.
u can even just use the self.db itself
self.cursor is not that necessary just makes it more convenient
that wont work, because u r using the context-manager, the connection would close, so they can't use it else where
it was an example i was gonna explain slowly ;-; that wont work in setup hook but if use with bot.start it will
ah ok π
@bot.command()
async def mute(ctx, user: nextcord.Member, time : int):
role1 = ctx.guild.get_role(985475444981764106)
role2 = ctx.guild.get_role(985205310740389918)
#print(ctx.guild.me.top_role > ctx.author.top_role)
if ctx.author.guild_permissions.administrator == True:
await user.remove_roles(role2)
await user.add_roles(role1)
await ctx.send(f'{ctx.member.mention}is now muted')
await asyncio.sleep(time*60)
await user.remove_roles(role1)
await user.add_roles(role2)
else:
await ctx.send("you are not administrator noob.")``` hi guys do you guys know why this isnt working? what i mean by that that it stops working after the 2nd await, like it doesnt send the message nor removes the role
Asher if i not use context manager will Code ewirk?
async def setup_hook(self):
self.db = aiosqlite.connect("prefixes.db")# <-- connection to db here
self.cursor = await self.db.cursor()# <-- connection to db cursor here
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)') # <-- refer to cursor as self.cursor
await self.db.commit() # <-- refer to db as self.db
async def get_prefix(self,message):
id = message.guild.id
await self.cursor.execute('')
await self.db.commit()
this should work
just as it is if u copy paster
also add this:
async def close(self):
await self.db.close()
super().close()
there may be a bug in self.cursor just run and check i havent used aiosqlite
shouldnt be using a single cursor all the time
that ends the point of having cursors in your database
cause sqlite allows you to perform operations with the connection itself
!d sqlite3.Connection.execute
execute(sql[, parameters])```
Create a new [`Cursor`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor "sqlite3.Cursor") object and call [`execute()`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor.execute "sqlite3.Cursor.execute") on it with the given *sql* and *parameters*. Return the new cursor object.
dead chat
No
...
replace msg with ctx
in () or not
in ()
@bot.event
async def on_message(ctx):
await ctx.send('hi')
Ye
alr now
how do make bot get input from user
acctualy wait i can do that
@bot.event
async def on_message(ctx):
if msg.content.startswith('+cookie'):
how can i make the bot wait for the next users message
acctualy wait
AttributeError: module 'discord.ext.commands' has no attribute 'event
Hi there. I found this project which allows to restore users using oauth2 in case of a raid, etc.
https://github.com/gamb2t/discord-restore-bot
I tried contacting the owner but everything is in Korean so I don't understand anything.
I translated the files and made a few modifications but I still need help making it work. Could anyone help me out?
I have put the modified version on a new GitHub repository.
I am able to run the bot.py file but whenever I press verify it doesn't do anything. I'm unsure how to get the access token+user id to add to the database.
https://github.com/vikingww2/oauth2-restore
Can anyone help me? (I'm happy to hop in vc to demonstrate the problem)
guys how do i i get input from a user
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
@bot.event
async def on_message(ctx):
if msg.content.startswith('+cookie'):
msg = await client.wait_for("message", check=check)
message = msg.content
like that?
message = msg.content
when you do msg.content = message ( you will get an name error if message is not defined ) but also you overwrite the content attribute
oh ok thank you
so if i run this
async def on_message(ctx):
if msg.content.startswith('+cookie'):
msg = await client.wait_for("message", check=check)
message = msg.content```
and i print message will it print out the message?
@shrewd apex
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix="@",help_command=None,intents=discord.Intents.all())
async def setup_hook(self):
self.connect = aiosqlite.connect("prefixes.db")
self.cursor = self.connect.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
async def get_prefix(self,message):
id = message.guild.id
await self.cursor.execute('')
await self.connect.commit()
Will it work?
change ctx to msg
kk
how do you get the help menu fields like this?
i cant figure out how to stack it like naruto botto has theirs
How can we give bot a prefix?
class botclass(commands.Bot):
def __init__(self):
super().__init__(intents=discord.Intents.all())
async def setup_hook(self):
self.connect = aiosqlite.connect("prefixes.db")
self.cursor = self.connect.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
async def get_prefix(self,message):
id = message.guild.id
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id))
prefix = await self.cursor.fetchone()
await self.connect.commit()
return prefix or '@'
#prefix function here
How to give a prefix after define bot?
super().__init__(command_prefix=self.get_prefix)
I am getting one error
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,intents=discord.Intents.all())
async def setup_hook(self):
self.connect = aiosqlite.connect("prefixes.db")
self.cursor = self.connect.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
async def get_prefix(self,message):
id = message.guild.id
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id))
prefix = await self.cursor.fetchone()
await self.connect.commit()
return prefix or '@'
bot = botclass()
Here is code
you have to await aiosqlite.connect and self.connect.cursor
I have to create new connection?
flat case for class names 
no the same
Oh understood
async def get_prefix(self,message):
id = message.guild.id
self.connect = aiosqlite.connect("prefixes.db")
self.cursor = self.connect.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id))
prefix = await self.cursor.fetchone()
await self.connect.commit()
return prefix or '@'
Like this?
await @robust fulcrum
await these, kind sir
Oh k
ashley sqlite3 classes
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,intents=discord.Intents.all())
async def setup_hook(self):
self.connect = await aiosqlite.connect("prefixes.db")
self.cursor = await self.connect.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
async def get_prefix(self,message):
id = message.guild.id
self.connect = await aiosqlite.connect("prefixes.db")
self.cursor = await self.connect.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id))
prefix = await self.cursor.fetchone()
await self.connect.commit()
return prefix or '@'
bot = botclass()
Now?
also this
you created another connection in the get_prefix function, which you should not be doing.
and don't commit on SELECT etc, commit is meant to be called only when you write something
oh smh
I said to not connect in get_prefix smh
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connect.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id))
prefix = await self.cursor.fetchone()
await self.connect.commit()
return prefix or '@'
Fine now?
nope
or maybe yes, depends on what you want
prefix there is a tuple with a single element and not a string
but that would work anyways
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
the placeholder values take a tuple, not an integer
I got this error
show your current code.
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,intents=discord.Intents.all())
async def setup_hook(self):
self.connect = await aiosqlite.connect("prefixes.db")
self.cursor = await self.connect.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connect.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.connect.commit()
return prefix or '@'
is that all the code you have?
No
import aiosqlite
import discord
from discord.ext import commands
import asyncio
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,intents=discord.Intents.all())
async def setup_hook(self):
self.connect = await aiosqlite.connect("prefixes.db")
self.cursor = await self.connect.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connect.commit()
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connect.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.connect.commit()
return prefix or '@'
bot = botclass()
@bot.event
async def on_ready():
print("ready")
@bot.command()
async def test(ctx):
await ctx.send("working")
Here is all
ight lemme see.
did you restart the bot?
Ye
hm lemme try
I am getting error in it can you help me fix
self.con = await aiosqlite.connect("prefixes.db") #<-- dont await
self.cursor = await self.con.cursor(
dont await this
Cursor?
dont re-use the cursor
!d discord.Client.connect
await connect(*, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
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.
haiiiiiiiiiiiiiiiiiii
yeah thats the issue
sarth new pfp
make it con
name it self.conn ;p
raven is a hottie
everyone knows self.conn and self.cur is tradition
idek who that is but hot
why use the same connection throughout the bot
0-0
π
π
*cursor
dc comics, teen titans
reusing the same cursor can cause multiple issues
to help save the environment β€οΈπ
oh damn... π³
uk who starfire is?
oh yeah that other hottie
change connection there also
me who used a dictionary for the first time
show updated code
I changed
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,intents=discord.Intents.all())
async def setup_hook(self):
self.connection = await aiosqlite.connect("prefixes.db")
self.cursor = await self.connection.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connection.commit()
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connection.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.connection.commit()
return prefix or '@'
bot = botclass()
then the error is lying
self.cursor = await self.connection.cursor()
await self.connection.commit()
do you use bot.run or bot.start
bot.run
self.connection = await aiosqlite.connect("prefixes.db")
self.cursor = await self.connection.cursor()
yeah then your setup hook never gets triggered
What to do now
it does i think
otherwise the error wont rise
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
bot.start('token')
This?
bot.run
async def main():
async with bot:
await bot.start('token')
asyncio.run(main())
the error itself is saying that there's no connection attribute yet
What kind of asynchronous sorcery is bot.start
bot.start() is basically the method called by bot.run() to start the bot
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,intents=discord.Intents.all())
async def setup_hook(self):
self.conn= await aiosqlite.connect("prefixes.db")
self.cursor = await self.conn.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.conn.commit()
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.conn.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
prefix = await self.cursor.fetchone()
await self.conn.commit()
return prefix or '@'
bot = botclass()
async def main():
async with bot:
await bot.start('token')
asyncio.run(main())
How to fix this?
ic but why even use that when you have run
if you installed discord.py with pip you shouldnt have done that
I did with git link
it still used pip, didnt it?
How to fix this
use poetry commands instead of pip.
Poetry in replit π
remove the async with bot:
thats not the issue
sync with?
they are on 1.7.3
does Bot even implement __aenter__ and __aexit__
and bot doesnt have an aenter and aexit in 1.7.3
Ah me in 1.7
Oof i forgot that it's my test bot π€£
How to fix it?
isnt that the latest stable release
indeed. someone provided them 2.0 code.
you should not be using setup_hook that way to connect then, just do this ```py
async def main():
await bot.setup_hook()
bot.run("token")
asyncio.run(main())
setup hook is automatically called once when the bot starts no need to call again
oh rip thats run
didnt see
they are on 1.7.3 :p
my bad
yep that works too
they told ash that they are using 2.0, so its not her fault either
i was just jokingπ
I should download 2.9?
2.0?
replace bot.run() with await bot.start()
you should, but if this fixes it, you dont need to
Anyone here tell me how to download 2.0 with pip?
you will need git to be installed
you cant ( in replit )
poetry add git+https://github.com/Rapptz/discord.py use this
that works only for once. when you restart the repl, it stops working
pip install git+https://github.com/Rapptz/discord.py.git should work
I have solution
add it to the poetry.lock or something
I just need to overite the poetry
os.system is the worst thing you should use.
thats not using pip
Bruh
this command does the same
You not able to understand what I mean
do you know how poetry works?
hey
getting this error trying to load cogs, /home/runner/pls-donate/cogs/robux.py:26: RuntimeWarning: coroutine 'BotBase.add_cog' was never awaited client.add_cog(lookup(client)) RuntimeWarning: Enable tracemalloc to get the object allocation traceback
code =
@client.event
async def on_ready():
print("loaded.")
print(client.user)
activity = discord.Game(name="PLS DONATE ", type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
for file in os.listdir("./cogs"):
if file.endswith(".py"):
try:
await client.load_extension(f"cogs.{file[:-3]}")
print(f"Loaded {file[:-3]}")
except Exception as e:
print(f"Failed to load {file[:-3]} because: {str(e)}")
you didnt await add_cog in your cog file's setup function
can you put it in code for me i dont get what ur saying
Why are u loading cogs on_ready
people from here like months back told me 2
U dont await add_cog
you didnt await bot.add_cog in your cog file's setup function?
oh
and stop naming Bots as client ffs
where do i put it
@slate swan i downloaded 2.0
why? is it bad? lol
lowercase b*
yes then you can now use bot.run() directly
!d discord.ext.commands.Bot ok lower it next time in your bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
uh
client is discord.Client bot is commands.Bot
python naming convention
@slate swan working but i need a set_prefix command now

commands.bot is a file
Sparky got owned
Sarth
in that case it will be commands.bot.Bot

class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
Can you help me sarth
Weird
yeah
yo wassup
does anyone here have some kind of unittesting framework for discord bots setup?
How should I make set_prefix command?
Hi
I used to use lower case b
How'd it go
Good
you mean like python tests?
Fine
yes i mean pythons unittest module
class FunCommands(commands.Cog):
^^^^^^^^^^^^
...
there probably arent any test frameworks for discord bots specifically but you can use pytest with pytest-asyncio
!pip dpytest
A package that assists in writing tests for discord.py
oh thanks
Alr I gtg π
π
well. first make a command that takes a new prefix argument from the author
your next aim would be writing the new prefix into the database using INSERT INTO table/UPDATE table , and commiting to the database
Ok
why
send the full error
How can I use the same connection in it?
bot.connection
if you have bot in your scope, else just use ctx.bot.connection
Oh k
!d select menus
This module provides access to the select() and poll() functions available in most operating systems, devpoll() available on Solaris and derivatives, epoll() available on Linux 2.5+ and kqueue() available on most BSD. Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.
Note
The selectors module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use the selectors module instead, unless they want precise control over the OS-level primitives used.
please do testing stuff in #bot-commands π
try:
connection = bot.connection
except NameError:
bot = ctx.bot
connection = bot.connection
finally:
globals()['bot'] = bot
π³

@bot.command()
async def set_prefix(ctx,newpre:str):
id = ctx.message.id
connection = ctx.bot.connection
cursor = connection.cursor()
Is it correct?
works, but await the connection.cursor()
but why do you need ctx.message.id
run a query using connection.execute
!d discord.ui.select
discord.ui.select(*, placeholder=None, custom_id=..., min_values=1, max_values=1, options=..., disabled=False, row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Select`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Select "discord.ui.Select") being used.
In order to get the selected items that the user has chosen within the callback use [`Select.values`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Select.values "discord.ui.Select.values").
For inserting prefix into guild I'd cell
message.id is the guild id ? huh
you named the class and function the same, so the function over writes the class
Oof i forgot
just move that class outside your cog class.
Do i need to select the value to insert?
#bot-commands pleasee
@robust fulcrum learn sql π
could you elaborate
Is there any guild join event?
@slate swan check dm!
if you mean the SELECT statement, you dont need that for inserting
on_guild_join
Say that again
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild") is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
The guild args is id of guild or name?
!d discord.Guild this object
class discord.Guild```
Represents a Discord guild.
This is referred to as a βserverβ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildβs hash.
str(x) Returns the guildβs name.
I mean the guild argument is id of guild or name?
a guild object
not id, not name, the discord.Guild object
like the one with guild.name thing yk
afjosdifgsoudfh;gouwea4dfn0w;
use guild.id for the id, guild.name for the name
When I do that, I get an error.
yeah
what's the error
the error says pretty much dosnt it
'cogs.tickets' raised an error: TypeError: cogs must derive from Cog
inherit from commands.Cog
also what rygua said
!e ```py
class ticket: ...
def ticket():...
print(type(ticket))``` your command function is overwriting the class
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'function'>
thats why we have naming conventions.
Where would I add commands.cog?
@dusky pine how can i make that when bot joins guild it inserts the '@' prefix into guild_id ?
How to make it
I have made the event but confused in inserting thing
class ticket(commands.Cog):
def __init__(self, bot):
self.bot = bot``` you define `ticket` as a cog
```py
@discord.slash_command(description = "Create a ticket")
async def ticket(ctx):
await ctx.respond("Test",view=MyView())``` and then assign that as a function.
which is not a cog .
That's why naming conventions are cool
π thats what i said but noone listens
flatcaseforeverythinggang
camel case when ?π
sussyCase
case insensitive when :troll:
stupid logging module, using camelCase
@slate swan me need some help can you?
They basically migrated it from some other language (java or js idr) but the question is why couldn't they just rename the stuff
sure. just post your issue here
did you random.shuffle(message.split())? /s
No
how can i make that when bot joins guild it inserts the '@' prefix into guild_id ?
How to make it
I have made the event but confused in inserting thing
if they renmaed it, people would be pissed of cuz now they have to edit their code
i was kidding lol
@slate swan check dms if u can

Can you help if possible
ctrl+shift+f ez π―π₯
Why didn't they rename it at first tho
in the bot join event ( google it )
just write a query to insert into the table the guild id and prefix
Ik about inserting in one value but not with 2
INSERT INTO table VALUES ( 69420(server id) , "@");
i dont think such conventions came out back then, and when it did it was too late
69420
ya tell millions of people to do that
didn't sql use single quotes
Why (server id)
they could provide both cases for some time with a deprecation message
How old is pep8
came out in 2001
And logging module?
insert the server id instead of 69420(server id)
hmm, they could, but i dont think response to that would be positive
Oh k
Can I use variable in server id?
they can atleast do that in python4 or something idk
Ok I found that stuff https://stackoverflow.com/questions/22993667/how-come-the-pythons-logging-module-doesnt-follow-pep8-conventions
!f-string use placeholders
!sql-fstring
SQL & f-strings
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
β’ Extended Example with SQLite (search for "Instead, use the DB-API's parameter substitution")
β’ PEP-249 - A specification of how database libraries in Python should work
@slate swan check dmmmmmm
I mean at the guild_id
dont ping me repeatedly for that, i'll check it when im finished here
oh no, they wont try stuff like that after the python2 to 3 incident, atleast thats what i sense from guido's tweet
sorry
add_cog(tickets(bot))
as long as a module follows one convention, it shouldn't be a big deal
too late now
rust is so organized man, everything i have used in rust follows convention
@bot.event
async def on_guild_id(guild):
id = guild.id
connection = ctx.bot.connection
cursor = connection.cursor()
await cursor.execute('INSERT INTO prefixtable VALUES ( ? , "@")',(id))
await connection.commit()
Is it correct?
run and see, rule 1 of programming
(id)
you forgot to put a comma
Ok
that's just a value not a tuple
use mypy/pyright strict when
i dont think "@" will work, try '@'
sql supports both strings
yeah, but "" in sql is something else
when i used pg it only accepted single quotes
embed=discord.Embed(color=color.color,description=f"you are missing the **permission(s)** ``" + ", ".join(error.missing_perms) + '``')
error
embed=discord.Embed(color=color.color,description=f"you are missing the **permission(s)** ``" + ", ".join(error.missing_perms) + '``')
AttributeError: 'MissingPermissions' object has no attribute 'missing_perms```
The SQL standard says that strings must use 'single quotes'
idk if sqlite supports double quotes for string
weird if it does
"" is use as an identifier
for table names column names etc
Pretty sure the library converts the quotations as necessary
ducky sqlite bruh
i guess so, lemme try using the same in mysql command line
ignore the 3rd query, i forgot to type VALUES there
Interesting
The set_prefix is returning none again and again even i updated the value
send the code
because you're checking the message.id in that function too
message.guild.id it should be ;-;
import aiosqlite
import discord
from discord.ext import commands
import asyncio
class botclass(commands.Bot):
def __init__(self):
super().__init__(command_prefix=self.get_prefix,intents=discord.Intents.all())
async def setup_hook(self):
self.connection = await aiosqlite.connect("prefixes.db")
print("connected")
self.cursor = await self.connection.cursor()
await self.cursor.execute('CREATE TABLE IF NOT EXISTS prefixtable(guild_id INTEGER ,prefix TEXT)')
await self.connection.commit()
async def get_prefix(self,message):
id = message.guild.id
self.cursor = await self.connection.cursor()
await self.cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
print("selected")
prefix = await self.cursor.fetchone()
print(prefix)
await self.connection.commit()
return prefix or '@'
bot = botclass()
@bot.event
async def on_guild_id(guild):
id = guild.id
connection = bot.connection
cursor = connection.cursor()
await cursor.execute('INSERT INTO prefixtable VALUES ( ? , "@")',(id,))
await connection.commit()
@bot.event
async def on_ready():
print("ready")
@bot.command()
async def test(ctx):
await ctx.send("working")
@bot.command()
async def set_prefix(ctx,newpre:str):
id = ctx.message.guild.id
connection = ctx.bot.connection
cursor = await connection.cursor()
await cursor.execute('UPDATE prefixtable SET prefix=? WHERE guild_id=?',(newpre,id,))
can you send the database file
Ok
dont think you can send here, just dm me
Hey @robust fulcrum!
It looks like you tried to attach file type(s) that we do not allow (.db). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
dont you have to commit after UPDATE?
I did
@robust fulcrum there's nothing in the db
you didnt in set_prefix
^^
Tf man why this happening
you can always check your sqlite files here to confirm the data
https://inloop.github.io/sqlite-viewer/
sqlite file viewer
you didnt commit in the set_prefix
I just did now
But it should insert value on guild join but it not did
kick and reinvite the bot while it's online
Ok
Float limit?
async def on_guild_id(guild):
id = guild.id``` its guild_join not guild_id
Or what is that
the first one is the index from which i should start selecting, the second one is the number of queries which the select should proceed with
i want make a bot on node.js
Ok
basically rows_in_table[:30]
thx @slate swan
exactly.
Why not just LIMIT 30
idk why they do that, the viewer had it by default :p
they have paginator which moves on to 30, 60 on the next page
you forgot to await something
Hmm
@bot.event
async def on_guild_join(guild):
id = guild.id
connection = bot.connection
cursor = connection.cursor()
await cursor.execute('INSERT INTO prefixtable VALUES ( ? , "@")',(id,))
await connection.commit()
cursor = connection.cursor()
await cursor.execute('INSERT INTO prefixtable VALUES ( ? , "@")',(id,))``` await connection.cursor when
Do we need to?
yes
Congrats to me
gg, so your custom prefix system works now?
Ye
π
π nice, now find a way to default a prefix if your bot was invited while the bot was offline
Head ache
Ye my bot returns @ if value is none
if its None and you try to setup a new prefix using set_prefix command, nothing will happen
since no row with that guild_id is in the database.
in your set_prefix you can fetch the prefix from the db first, if its there, then update it
if its not there , then insert it, easy
for some reason this get_role is returning None and I'm not sure why. ik it can see Config().further_sup... bc itlogs the value when it errorspy @button(label="I still need help!", style=ButtonStyle.blurple, custom_id="Further-Support",, emoji="π©",, row=2,) async def role_add_button(self, interaction: Interaction, button: Button): # get_role from the clients cache role = interaction.guild.get_role(Config().further_support_role)
is that a string?
yes it probably will be bc it's pulling it from the.env
Just wrap it in int() and I should be good, I think
os.getenv(key, default=None)```
Return the value of the environment variable *key* if it exists, or *default* if it doesnβt. *key*, *default* and the result are str. Note that since [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") uses [`os.environ`](https://docs.python.org/3/library/os.html#os.environ "os.environ"), the mapping of [`getenv()`](https://docs.python.org/3/library/os.html#os.getenv "os.getenv") is similarly also captured on import, and the function may not reflect future environment changes.
On Unix, keys and values are decoded with [`sys.getfilesystemencoding()`](https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding "sys.getfilesystemencoding") and `'surrogateescape'` error handler. Use [`os.getenvb()`](https://docs.python.org/3/library/os.html#os.getenvb "os.getenvb") if you would like to use a different encoding.
[Availability](https://docs.python.org/3/library/intro.html#availability): most flavors of Unix, Windows.
key, default and the result are str.
How can I do that? Any idea?
yes, first try getting the prefix for that server using the code you in the get_prefix, if fetchone() returns None, then use INSERT INTO prefixtable, else use UPDATE prefixinfo
it's fetchone() without an underscore
*without
faster I am
ty for correcting me
indeed
human you are, cant compete me
I wonder why it doesn't have an underscore π€ maybe because it was ported from another language?
Probably
@client.command()
async def wiki(ctx, keyword):
front = "https://en.wikipedia.org/wiki/"
await ctx.send(front + keyword)
client.run("(token)", bot=True)
status = cycle(['A', 'B'])
What can I do to solve this error?
what doesn't?
Remove bot=True, that kwarg was removed in newer versions
The fetchone method
Ok
Still error
oh
Your using an invalid token
Yeah it's not the client secret
nope
Go to the bot page, copy the bot token
token is visible only once when u create the application
Actually regenerate to copy it
after that u have to reset and copy
@bot.command()
async def set_prefix(ctx,newpre:str):
id = ctx.message.guild.id
connection = ctx.bot.connection
cursor = await connection.cursor()
await cursor.execute('SELECT prefix FROM prefixtable WHERE guild_id=?',(id,))
check = await cursor.fetchone()
if check == None:
await cursor.execute('INSERT INTO prefixtable VALUES ( ? , ?)',(id,newpre,))
await ctx.send(f"prefix updated to {newpre}")
await connection.commit()
else:
await cursor.execute('UPDATE prefixtable SET prefix=? WHERE guild_id=?',(newpre,id,))
await ctx.send(f"prefix updated to {newpre}")
await connection.commit()
Like this?
exactly !
Thanks for help
I never thought i would make this thing
mhhh
probably replace check == None with check is None
Lots of redundant code
yes the await ctx.send and connection. commit can be moved out of the if/else
Both have same meaning ig?
!d is
id = ctx.message.guild.id
connection = ctx.bot.connection
cursor = await connection.cursor()``` and these var
prefer using is for comparing with singletons
Not entirely
ofcourse.
I confused how to
just like any other command...
Oh k
is checks if its the same object, == checks if they contain the same value
hence why is is a little faster than == to check for singleton values
And do i need to delete the prefix and guild I'd on guild remove?
Do event name is on_guild_remove?
yes
yds
I tried to use the correct one, the bot can run but it don't reply me anything
I mean that the storage will be like wasted on the non used value
no
thats not even 0.01kb
barely seems to exist
Replit gives only 1 gb sadly
1gb is more than enough
Ik
it's not 10 records will fill up a gb
cause they will just purge your files since their file system is ephemeral
My bot is already 89 mb
"89"
bruh one row with two columns takes like 64 bytes
probably less depending on the data type
But i would prefer deleting
i bet most of that is pycache lol
you know what takes 64 bytes? empty dict
64 byte also precious
you know even if you have more than 500 rows with max 2 cols, you will still be left with roughly 250+mb (if I calced it right sooo)
My precious
Whats pychache
reminds me of the goblin π
bro, a class is like 1000+ bytes, and you must have like 5-6 in ur whole bot, why do you care for one sql row so much?
python to bytecode
green
Clean and python
ew
haha people care about n bytes in code
my docstrings will probably take up 20%
just ask
@robust fulcrum my db file with 10000 guild, prefix items takes 156 kb
How to delete the prefix and guild I'd from db?
DROP
I have delete ig not drop?
yes.
DELETE ...;DROP table π
make him drop the complete table
Me rn doing !set_prefix @'; DROP TABLE prefixtable;--
can't forget the classic ;--
dont do that lol
My bot can run but it doesn't respond
put the command inside the cog class
Ik about deleting 1 value but not 2
you dont delete values, you delete rows
self, interaction
self, ctx cuz pycord
they provide a ApplicationContext or something class as the first arg instead of interaction
How?
DELETE FROM table_name WHERE field = ?
I want delete guidl_id and prefix will it delete both?
yep
I thought only 1
it deletes both
it deletes the whole row
uwu
@slate swan
There is one problem
Like someone kicks the bot when it's offline then the prefix would not be removed from table
Is there any way to fix?
you can make a separate script to delete the rows in the db which the bot is not in
when making a ticket bot, how do you set the permissions for it?
Not possible to
it's possible lol, what are u talking about
Like someone kicks the bot when it's offline then the prefix would not be removed from table
You can make a script to check if the bot is not in that server
Hard for me
when making a ticket bot, how do you set the permissions for it?
permissions for the bot itself, or the created tickets?
how can i copy a message one channel to another channel?
take the message content, and send it to a different channel
which message do you want to send to another channel?
created tickets
assuming you're using discord.py, the Guild.create_text_channel() method has an overwrites= parameter that takes a dictionary of PermissionOverwrite objects so you can specify the permissions for @Π΅veryone, whoever made the ticket, and whatever roles should be allowed to see it
I use nextcord but should be similar
e.g. py overwrites = { ctx.guild.default_role: discord.PermissionOverwrite(read_messages=False), ctx.author: discord.PermissionOverwrite(read_messages=True), my_mod_role: discord.PermissionOverwrite(read_messages=True) } await ctx.guild.create_text_channel(overwrites=overwrites, ...)
Okay thank you
@hushed galleon 1 more thing, do you know how to also send a message in the created channel?
or even on the ephemeral pinging the new channel?
so upon interaction sends the new channel in the ephemeral
create_text_channel returns channel object
yeah ik that
you could do py channel = await ctx.guild.create_text_channel(overwrites=overwrites, ...) await channel.send('hello')
ah ok
And you can't send an ephemeral without interaction if you meant that

whos nae-nae?
Download "Watch Me (Whip/Nae Nae)" here: http://smarturl.it/WatchMeSingle
Listen to Watch Me (Whip/Nae Nae)" on Spotify: http://smarturl.it/WatchMeSpotify
Official video for βWatch Me (Whip/Nae Nae)β directed by Marc Klasfeld and produced by Cisco Newman and Danny Lockwood
Follow SilentΓ³:
Twiiter: http://twitter.com/therealsilento
IG: http://i...
@bot.command(pass_context=True)
async def test(ctx):
MEMBER = discord.utils.get(ctx.guild.roles, name= "Member")
embed=discord.Embed(title="Verification", description="You are now Verified!", color=0x3EF72D)
if ctx.channel.id == 993228727846719569:
await ctx.author.add_roles(MEMBER)
await ctx.message.delete()
await ctx.send(embed=embed, delete_after=5)
and
@bot.event
async def on_message(ctx):
if ctx.content != "verify": #Check if the message is not exactly "verify" (the verify message/command sent by the user).
print("Deleting because it's not $verify")
await ctx.delete()
How would i combine these two as everything i've tried makes one work but not the other?
Hey
i am trying to study discord bot programming but i have error
what i have to do with it?
maybe you can hellp
will be so gratefull about it
FAQ: https://discordpy.readthedocs.io/en/stable/faq.html#why-does-on-message-make-my-commands-stop-working
your on_message event is preventing all commands from being processed so you should use one of the solutions described in the faq, either @bot.listen() or await bot.process_commands(message)
thank youπ
hey is there any good tutorial on discord.py library?
!ot
Off-topic channel: #ot2-never-nesterβs-nightmare
Please read our off-topic etiquette before participating in conversations.
@bot.command(pass_context=True)
async def verify(ctx):
MEMBER = discord.utils.get(ctx.guild.roles, name= "Member")
embed=discord.Embed(title="Verification", description="You are now Verified!", color=0x3EF72D)
if ctx.channel.id == 993228727846719569:
await ctx.author.add_roles(MEMBER)
await ctx.message.delete()
await ctx.send(embed=embed, delete_after=5)
@bot.listen('on_message')
async def verify(ctx):
if ctx.content != "$verify":
print("Deleting because it's not $verify")
await ctx.delete()
Still wont workπ§
have you been to this channel before lmaoo
Wdym I have 8952 messages in this channel π‘
async def ping(interaction : Interaction):
await interaction.response.send_message("pong")``` hi guys this is my first slash command so im sorry if iam dumb but did i do something wrong? if i type /ping or look at the slash commands my command will not be displayed
anyone know how to delete a channel through interaction?
wait i thought pass_context=True isnt a thing anymore
what doesnt work?
it still exists, just that it defaults to True now so there's no point in setting it to True yourself
oh ok, btw hi zeffo
could u maybe help me with my problem?
It's ctx.message.content
sure, ask away
See
.
@vocal snow
commands.Context
wAHT
Ye
what
Thank you!
async def on_message(message):
guild = message.guild
role = guild.get_role(985205310740389918)
if message.author == bot.user:
return
if message.channel.id == 987651665492586568 and message.content.lower() != "!verify":
await message.delete()
await message.channel.send(f'{message.author.mention}please only write !verify and not something other', delete_after=3)
if message.channel.id == 987651665492586568 and message.content.lower() == "!verify":
await message.author.add_roles(role)
await message.delete()
await bot.process_commands(message)
``` i have something similar idk if this could help you
which wrapper is this?
nextcord.
should i rather use discord?
i only use nextcord because a friend said to me nextcord is better
i use nextcord
Dont
Appreciate it
That's upto preference but I'm not familiar with nextcord. I'll need to check out their docs
oh okay
Use disnake or discord.py nextcord is ew
why?
Suggestion
is there a delete command similar to attachments.save?
Delete from disk or delete the attachment message
how do i delete a channel thru an interaction? im trying to freshen up my ticket system.
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
!d discord.TextChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
the former
because it messes if I use the command again and produces two juxtaposed images
no then, make your own
await message.channel.send(f"Please enter your code below. Your code: '{random.randint (10000,99999)}'")
embed=discord.Embed(title="Verification", description="You are now Verified!", color=0x3EF72D)
await message.author.add_roles(role)
await bot.process_commands(message)
await message.channel.send(embed=embed, delete_after=5)
This is a part of my verification system. How would i go about checking if the random number is correct and then that resulting into the role adding?
How to get a channel's webhook and send a message through it
wdym by "checking if the random number is correct"?
I think i've figured it out. But basically {random.randint(10000,99999)} gives out a 'code', user has to enter code and if its right it will give them a role
Nevermind not figured it out
What are you verifying with this though?
store the random number somewhere, then check use it to check
How to get webhook by url
!d discord.Webhook.from_url
classmethod from_url(url, *, session, bot_token=None)```
Creates a partial [`Webhook`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook "discord.Webhook") from a webhook URL.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") instead of `InvalidArgument`.
its from_url not url
vs code
Save the random number to a variable
Oops, I just tried another option and forgot to put it back. Error remains
try this
async with aiohttp.ClientSession() as session:
webhook = discord.Webhook.from_url(url, session=session)
you're passing the ClientSession class to session kwarg, not an instance
Full code:
@bot.event
async def on_message(message):
guild = message.guild
role = guild.get_role(993231458846122014)
code = {random.randint (10000,99999)}
if message.author == bot.user:
return
if message.channel.id == 993228727846719569 and message.content.lower() != "$verify":
await message.delete()
await message.channel.send(f' Please only write $verify and not something other {message.author.mention}', delete_after=3)
if message.channel.id == 993228727846719569 and message.content.lower() == "$verify":
message = await message.channel.send('React to recieve your code!')
await message.add_reaction('β
')
def check(reaction, user):
return reaction.emoji == 'β
' and reaction.message == message
reaction, user = await bot.wait_for('reaction_add', timeout=30.0, check=check)
await message.delete()
await message.channel.send(f"Please enter your code below. Your code: '{code}'")
embed=discord.Embed(title="Verification", description="You are now Verified!", color=0x3EF72D)
await message.author.add_roles(role)
await bot.process_commands(message)
await message.channel.send(embed=embed, delete_after=5)
Saved the random number as a variable now thanks, so how would i go about checking if its right or not now?
hi robin π
dont do {random.randint(...)} the {} outside makes a set which is not what you want, just do random.radint(...)
thank you
Hi. Nice to see you all, been a while
done that thanks, so now how do I take the input, check if its correct and then give the role?
so you need to store it in a global space or an external file, because everytime someone types a message, it generates a new random int, which is not what you want
like you can either have a global dict/list where you store the random ints or you write those ints to a file and then you open the file and look for it
advantage of file is that it will keep the data even after your bot shuts down ( unless you wipe it yourself )
π
from random import randint
data = {}
def store_data(name):
data[name] = randint(1, 10)
return 'stored'
store_data('ryuga')
store_data('mossy')
print(data)
something like this
whats is the code to have the bot avatar ? please
Appreciate it
you didnt pass the message parameter
bot.avatar.url ?
oh, you want to use events in cogs, for that you need to decorate it with @commands.Cog.listener()
bot.user.avatar.url
thanks you, did you know the code to show all the servers the bot have ?
bot.guilds
@commands.user_command(name="balance", guild_ids=GUILD_IDS, description="get users balance user")
@commands.check(check_user_in_db)
@commands.check(check_target_not_bot)
async def balance(self, inter: Inter, target: disnake.Member):
await inter.response.defer()
async with inter.channel.typing():
em = await self.economy_service.balance(target)
await inter.send(embed=em)
why are the type hints not working for inter.response and inter.channel
because you are sending the message in message.channel not create_channel
wdym by "not working"
I'm confused, are you looking for autocorrect suggestions?
auto-what ππ yes yes im looking for those
Hi
no, i don't think you want that check, just do create_channel.send(message)
suggestions for what method? your custom methods don't show up in the tab?
just follow the standard 