#discord-bots

1 messages Β· Page 1142 of 1

slate swan
#

!d discord.Guild

unkempt canyonBOT
#

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.
slate swan
#

well try updating the library

pastel solar
#

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

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
slate swan
#

you would need atleast the ID to do this

slate swan
#

if that doesnt work, use git to install their master branch

pastel solar
pliant pagoda
#

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πŸ™‚

slate swan
#

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

pliant pagoda
#

i see, thank you and apologies if i've been 'difficult'πŸ˜†

scarlet aurora
#

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()```
iron sorrel
#

guys I'm asking for a friend,

did they remove the ability to selfbots finally? thank god no more abusers

maiden fable
#

Yea...

iron sorrel
#

when did they? and can i read the patch notes? my friend is really interested

#

not me pff never break tos

maiden fable
#

You can tell your friend to ask here instead of asking some other friend to ask here

pliant gulch
#

You can still selfbot

#

Not that I mean you should selfbot, but you can

iron sorrel
#

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?

pliant gulch
#

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

iron sorrel
#

am i sitting on a websocket connection rn then?

pliant gulch
#

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

iron sorrel
#

discord does use it for bots, i know that but when you post messages on the web discord it sends web requests, iirc

pliant gulch
#

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

pliant gulch
#

Mhm

cloud beacon
#
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
torn sail
#

!d discord.Intents.message_content

unkempt canyonBOT
#

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...

flat solstice
#

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,)
silent portal
#

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...
south needle
silent portal
south needle
#

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.

desert heart
#

It's just the asynchronous nature of things.

slender perch
#

how would i make a website for managing a discord bot?

old gate
#

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

slate swan
#

they still exist

#

ik a website people use (not gonna say obv) but they still work just not how they use to be

slate swan
#

i mean we all had to of use a self bot once before

slate swan
#

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

south needle
#

!d discord.Guild.vanity_invite

unkempt canyonBOT
#

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.
silent portal
#

is there a way to check if a message has a discord invite?

south needle
silent portal
south needle
#

yeah exactly

silent portal
#

?

#

ok ty

#

and can I check if the invite sent is the invite to the server the message has been sent to?

south needle
#

I don't know if you can check what server the invite link is from

silent portal
#

okok ty

south needle
#

ofc

#

!d discord.Guild.edit

unkempt canyonBOT
#
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...
south needle
#

guild.vanity_invite() returns the vanity with the discord.gg is there a way to remove that and just get the vanity by itself?

fading marlin
#

strip it off?

slate swan
south needle
#

ahh forgot about strip() for a second

slate swan
#

guys is there slash command in dpy

#

can someone help?

paper sluice
slate swan
#

cannot import app_commands from discord.ext

#

@paper sluice

robust fulcrum
#
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 ?

slate swan
#

what kind of real time data are we talking about?

robust fulcrum
#

@slate swan

#

I need some help

slate swan
#

nice cm logic

robust fulcrum
#

Oh k

slate swan
#

it will run automatically now

robust fulcrum
#

Is code correct?

slate swan
#

sql query is wrong, should have a comma in between of fields

robust fulcrum
#

Oh k

slate swan
#

I gotta continue studying bye

robust fulcrum
#
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()
robust fulcrum
robust fulcrum
#

Now

#

How can I use the same connecttion everywhere?

slate swan
#

self.connect

#

or bot.connect if outside the class

robust fulcrum
#

I'll do in class

junior forum
#
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)β€Š
robust fulcrum
junior forum
#

It doesn't post the webhook and no errors either

robust fulcrum
junior forum
#

Ye

robust fulcrum
#

Use ```py

junior forum
#

I did

robust fulcrum
#

To make it python code block

junior forum
#

I'm on mobile so is tricky rn

robust fulcrum
#

Me also on mobile

junior forum
#
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

robust fulcrum
#

Ye

#

It helps the helper to understand

junior forum
robust fulcrum
#

Me noob at python

swift pumice
#

@robust fulcrum From where are you if i could ask?

#

You dont need to answer the question if you dont want to

swift pumice
#

no country

robust fulcrum
#

India

swift pumice
#

Oh okay

slate swan
#

also, what the issue?

vale wing
#

Ah yes f"{stuff}"

#

Original way of casting to str

slate swan
slate swan
slate swan
#

πŸ₯‚ i'd rather use httpx

slate swan
#

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

left idol
#

is there a limit to how many choices i have in an autofill?

slate swan
#

XMLHttpRequest better πŸ˜”

slate swan
#

depends on wym by autofill

slate swan
left idol
#

autocomplete?

slate swan
#

js ❀️

slate swan
#

cursed * 100

#

shut up

left idol
#

it should be autocomplete

slate swan
left idol
#

yea autocomplete

slate swan
#

js users try to use 109 of them

left idol
#

so it displays 25 but i can always just input the rest?

#

like it shows the first 25 options

shrewd apex
#

yep

slate swan
#

it doesnt show up magically, you gotta provide a logic to your autocomplete for that.

left idol
#

what do you mean

shrewd apex
#

a list comp generally

left idol
#

ye i have all my options in a list

slate swan
left idol
#

im using pycord

slate swan
left idol
#
async def autofill(ctx: discord.AutocompleteContext, choices):
    return [auto for auto in choices]
left idol
#

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

slate swan
#

use [:25] to get the first 25 elements in the list then...

shrewd apex
#

it would but u can show only 25

slate swan
left idol
#

i just didn't know if there was a limit for that part

shrewd apex
#

mostly 25 is limit 25 button 25 select option 25 reactions

left idol
#

are buttons 5x5 grid?

slate swan
#

basic python.

left idol
#

or can i have 2 rows of 10 or something

shrewd apex
#

u cant select like that it depends on button size

slate swan
#

you cant have more than 25 items in a view, a select menu is treated as 5items btw

left idol
#

ohh ok

#

thank you fellas

shrewd apex
#

np

slate swan
#

discord is so obsessed with 25 limits

shrewd apex
#

indeed

#

it would be best if they removed that and the ratelimits

slate swan
#

yeah, and next day see dank memer with 1000 buttons

slate swan
vale wing
#

Literal football field

slate swan
#

indeed lmao

slate swan
#

How do I DM a user after the did a command?

slate swan
unkempt canyonBOT
#
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**.
slate swan
slate swan
slate swan
slate swan
#

anyone know what i did wrong? ik i def did sum wrong

slate swan
slate swan
#

ah okay is that all?

#

should prob try it first nvm

#

man literally entered iterable there ;-;

#

thought thats what they meant 😭

vale wing
#

Sus

#

Just random.randint(0, 1) dude

#

Iirc both bounds are inclusive

slate swan
#

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

vale wing
#

!e

import random
def coinflip():
    print("Heads" if random.randint(0, 1) else "Tails")

for i in range(5):
    coinflip()```
#

Love internet here

slate swan
vale wing
#

Takes fricking minute to send a message

#

Why is it so slow 😭

slate swan
#

🍿

robust fulcrum
slate swan
#

what's self.message?

robust fulcrum
#

In a class

robust fulcrum
slate swan
robust fulcrum
#

Oh k

robust fulcrum
slate swan
robust fulcrum
#

Not much

#

Me watching classes videos yet and learning

robust fulcrum
vocal snow
#

Learning OOP before doing this would make things easier

robust fulcrum
#

But how to make that work

#

I am learning

shrewd apex
robust fulcrum
#

But Ashley told to use same connection

shrewd apex
#

u didnt even create a connection u used a context manager ;-;

slate swan
#

^

shrewd apex
#

show ur setup hook code

robust fulcrum
#
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?

shrewd apex
#
   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

paper sluice
swift pumice
#

.

shrewd apex
#

u can even just use the self.db itself

#

self.cursor is not that necessary just makes it more convenient

paper sluice
shrewd apex
paper sluice
#

ah ok πŸ‘

swift pumice
#

@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
robust fulcrum
shrewd apex
#
   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

paper sluice
#

also add this:

async def close(self):
    await self.db.close()
    super().close()
shrewd apex
#

there may be a bug in self.cursor just run and check i havent used aiosqlite

slate swan
#

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

unkempt canyonBOT
#

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.
swift pumice
#

dead chat

left vector
#

how send bot message

#

simple just how do i make the bot say a message

gleaming heath
#

await ctx.send('...')

#

With an await function with ctx param

left vector
#

@bot.event
async def on_message(msg):
await ctx.send('hi')

#

like that?

gleaming heath
#

No

left vector
#

...

gleaming heath
#

replace msg with ctx

left vector
#

in () or not

gleaming heath
#

in ()

left vector
#

@bot.event
async def on_message(ctx):
await ctx.send('hi')

gleaming heath
#

Ye

left vector
#

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

full valley
#

bro read the docs

#

then ask

covert basin
paper sluice
#

why do you have bot = client = commands

#

just directly do

bot = commands.Bot(<...>)
frail notch
#

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)

left vector
#

guys how do i i get input from a user

slate swan
unkempt canyonBOT
#

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**...
left vector
#
@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?

paper sluice
#

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

left vector
#
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?

robust fulcrum
#

@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?

left vector
#

kk

nocturne topaz
#

how do you get the help menu fields like this?

#

i cant figure out how to stack it like naruto botto has theirs

robust fulcrum
#

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?

left vector
slate swan
robust fulcrum
#
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

slate swan
robust fulcrum
paper sluice
slate swan
robust fulcrum
#

Oh understood

robust fulcrum
# slate swan no the same
    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?

slate swan
robust fulcrum
#

Oh k

slate swan
#

ashley sqlite3 classes

robust fulcrum
#
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?

slate swan
#

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

robust fulcrum
# slate swan 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?

slate swan
#

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

slate swan
#

the placeholder values take a tuple, not an integer

slate swan
robust fulcrum
# slate swan 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 '@'
slate swan
#

is that all the code you have?

robust fulcrum
robust fulcrum
# slate swan is that all the code you have?
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

slate swan
#

ight lemme see.

robust fulcrum
#

Ye

slate swan
#

hm lemme try

robust fulcrum
#

@slate swan

#

Can you help pls

robust fulcrum
shrewd apex
#
        self.con = await aiosqlite.connect("prefixes.db") #<-- dont await
        self.cursor = await self.con.cursor(
#

dont await this

slate swan
#

!d discord.Client.connect

unkempt canyonBOT
#

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.
dusky pine
#

haiiiiiiiiiiiiiiiiiii

slate swan
#

yeah thats the issue

dusky pine
#

sarth new pfp

slate swan
#

stop naming it connect.

#

change it to self.connection or something

robust fulcrum
#

Ok

shrewd apex
#

make it con

dusky pine
#

name it self.conn ;p

slate swan
dusky pine
#

everyone knows self.conn and self.cur is tradition

dusky pine
slate swan
#

why use the same connection throughout the bot

shrewd apex
#

0-0

slate swan
#

πŸ˜”

robust fulcrum
slate swan
slate swan
lament mesa
dusky pine
dusky pine
shrewd apex
dusky pine
#

oh yeah that other hottie

shrewd apex
#

change connection there also

slate swan
slate swan
robust fulcrum
#
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()
shrewd apex
#

then the error is lying

#

self.cursor = await self.connection.cursor()

#

await self.connection.commit()

slate swan
robust fulcrum
#

bot.run

shrewd apex
#

self.connection = await aiosqlite.connect("prefixes.db")
self.cursor = await self.connection.cursor()

slate swan
#

yeah then your setup hook never gets triggered

robust fulcrum
#

What to do now

shrewd apex
#

otherwise the error wont rise

slate swan
unkempt canyonBOT
#

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")...
robust fulcrum
#
bot.start('token')

This?

dusky pine
#

bot.run

slate swan
slate swan
dusky pine
#

What kind of asynchronous sorcery is bot.start

slate swan
shrewd apex
#
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())
robust fulcrum
#

How to fix this?

dusky pine
slate swan
#

if you installed discord.py with pip you shouldnt have done that

robust fulcrum
slate swan
#

it still used pip, didnt it?

robust fulcrum
slate swan
#

use poetry commands instead of pip.

robust fulcrum
#

Poetry in replit πŸ’€

lament mesa
slate swan
robust fulcrum
#

sync with?

slate swan
#

they are on 1.7.3

lament mesa
#

does Bot even implement __aenter__ and __aexit__

slate swan
#

and bot doesnt have an aenter and aexit in 1.7.3

robust fulcrum
#

Ah me in 1.7

lament mesa
#

whats the use of it though

#

cleanup i guess

robust fulcrum
#

Oof i forgot that it's my test bot 🀣

robust fulcrum
lament mesa
slate swan
slate swan
# robust fulcrum How to fix it?

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())

shrewd apex
#

oh rip thats run

#

didnt see

shrewd apex
#

my bad

lament mesa
#

just override run

#

or the start method

slate swan
#

yep that works too

#

they told ash that they are using 2.0, so its not her fault either

shrewd apex
#

i was just jokingπŸ˜”

slate swan
#

you should, but if this fixes it, you dont need to

robust fulcrum
#

Anyone here tell me how to download 2.0 with pip?

lament mesa
#

you will need git to be installed

slate swan
#

poetry add git+https://github.com/Rapptz/discord.py use this

robust fulcrum
#

I downloaded 2.0 in my main bot

slate swan
#

that works only for once. when you restart the repl, it stops working

lament mesa
lament mesa
#

add it to the poetry.lock or something

robust fulcrum
#

I just need to overite the poetry

slate swan
#

os.system is the worst thing you should use.

slate swan
robust fulcrum
#

Bruh

slate swan
robust fulcrum
#

You not able to understand what I mean

slate swan
#

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

slate swan
slate swan
#

oh

#

and stop naming Bots as client ffs

#

where do i put it

robust fulcrum
#

@slate swan i downloaded 2.0

slate swan
slate swan
slate swan
slate swan
unkempt canyonBOT
#

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.
slate swan
#

uh

slate swan
#

python naming convention

robust fulcrum
#

@slate swan working but i need a set_prefix command now

supple thorn
lament mesa
#

commands.bot is a file

supple thorn
#

Sparky got owned

slate swan
#

^

#

okay but now what do i do for my cogs?

robust fulcrum
#

Sarth

lament mesa
supple thorn
slate swan
#

Bro

#

!d discord.ext.commands.bot.Bot

unkempt canyonBOT
#

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.
robust fulcrum
#

Can you help me sarth

slate swan
#

Weird

slate swan
slate swan
iron sorrel
#

does anyone here have some kind of unittesting framework for discord bots setup?

robust fulcrum
supple thorn
#

Hi

slate swan
#

I used to use lower case b

supple thorn
slate swan
#

Good

slate swan
#

Fine

iron sorrel
slate swan
#

wth does this mean?

#

cogs must derive from Cog

#

Anyways

#

My bad sarth

iron sorrel
#
class FunCommands(commands.Cog):
                  ^^^^^^^^^^^^
  ...
lament mesa
slate swan
unkempt canyonBOT
iron sorrel
slate swan
#

Alr I gtg πŸ‘‹

paper sluice
#

πŸ‘‹

slate swan
#

your next aim would be writing the new prefix into the database using INSERT INTO table/UPDATE table , and commiting to the database

robust fulcrum
#

Ok

dull terrace
lament mesa
#

send the full error

robust fulcrum
slate swan
#

if you have bot in your scope, else just use ctx.bot.connection

robust fulcrum
#

Oh k

errant coral
#

!d select menus

unkempt canyonBOT
#

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.

slate swan
#

please do testing stuff in #bot-commands πŸ˜„

paper sluice
lament mesa
robust fulcrum
slate swan
lament mesa
slate swan
#

!d discord.ui.select

unkempt canyonBOT
#

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").
robust fulcrum
slate swan
paper sluice
#

you named the class and function the same, so the function over writes the class

robust fulcrum
slate swan
#

just move that class outside your cog class.

robust fulcrum
slate swan
#

#bot-commands pleasee

dusky pine
#

@robust fulcrum learn sql πŸ˜„

slate swan
robust fulcrum
#

Is there any guild join event?

slate swan
#

@slate swan check dm!

#

if you mean the SELECT statement, you dont need that for inserting

lament mesa
dusky pine
lament mesa
#

!d discord.on_guild_join

unkempt canyonBOT
#

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.
robust fulcrum
slate swan
#

!d discord.Guild this object

unkempt canyonBOT
#

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.
robust fulcrum
#

I mean the guild argument is id of guild or name?

dusky pine
#

a guild object

#

not id, not name, the discord.Guild object

#

like the one with guild.name thing yk

#

afjosdifgsoudfh;gouwea4dfn0w;

lament mesa
pastel solar
robust fulcrum
dusky pine
slate swan
#

the error says pretty much dosnt it

#

'cogs.tickets' raised an error: TypeError: cogs must derive from Cog

paper sluice
#

inherit from commands.Cog

slate swan
#

also what rygua said

#

!e ```py
class ticket: ...

def ticket():...

print(type(ticket))``` your command function is overwriting the class

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

<class 'function'>
slate swan
#

thats why we have naming conventions.

pastel solar
#

Where would I add commands.cog?

robust fulcrum
#

@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

slate swan
# pastel solar Where would I add commands.cog?
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 .

vale wing
#

That's why naming conventions are cool

slate swan
paper sluice
#

flatcaseforeverythinggang

shrewd apex
#

camel case when ?πŸ‘€

vale wing
#

sussyCase

slate swan
#

case insensitive when :troll:

paper sluice
#

stupid logging module, using camelCase

robust fulcrum
#

@slate swan me need some help can you?

vale wing
slate swan
#

sure. just post your issue here

paper sluice
robust fulcrum
paper sluice
slate swan
#

@slate swan check dms if u can

paper sluice
robust fulcrum
dusky pine
vale wing
paper sluice
robust fulcrum
slate swan
paper sluice
vale wing
#

69420

paper sluice
dusky pine
robust fulcrum
slate swan
vale wing
#

How old is pep8

paper sluice
vale wing
#

And logging module?

slate swan
paper sluice
robust fulcrum
#

Oh k

robust fulcrum
slate swan
vale wing
slate swan
#

!sql-fstring

unkempt canyonBOT
#

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
#

@slate swan check dmmmmmm

robust fulcrum
slate swan
#

dont ping me repeatedly for that, i'll check it when im finished here

paper sluice
slate swan
#

add_cog(tickets(bot))

paper sluice
#

as long as a module follows one convention, it shouldn't be a big deal

slate swan
#

there are some other modules too

#

but i cant think of one rn

paper sluice
#

rust is so organized man, everything i have used in rust follows convention

dusky pine
#

ugh rust

#

the new cool kid

robust fulcrum
#
@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?

paper sluice
dusky pine
robust fulcrum
#

Ok

dusky pine
#

that's just a value not a tuple

slate swan
#

use mypy/pyright strict when

dusky pine
#

use mypy without ignore_missing_imports when

#

mypy basically unusable without it :P

lament mesa
paper sluice
#

huh?

#

it would just break the string

slate swan
#

sql supports both strings

lament mesa
dusky pine
#

when i used pg it only accepted single quotes

slate swan
#
      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```
lament mesa
#

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

slate swan
lament mesa
#

weird

#

ducky_sqlite just follow the standard lemon_clown

vocal snow
# slate swan

Pretty sure the library converts the quotations as necessary

slate swan
#

ignore the 3rd query, i forgot to type VALUES there

vocal snow
#

Interesting

robust fulcrum
slate swan
robust fulcrum
#
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,))
robust fulcrum
#

Ok

slate swan
#

dont think you can send here, just dm me

unkempt canyonBOT
#

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.

paper sluice
#

dont you have to commit after UPDATE?

robust fulcrum
slate swan
#

@robust fulcrum there's nothing in the db

paper sluice
#

you didnt in set_prefix

slate swan
robust fulcrum
slate swan
slate swan
robust fulcrum
#

I just did now

robust fulcrum
slate swan
robust fulcrum
#

Ok

vale wing
slate swan
#
async def on_guild_id(guild):
    id = guild.id``` its guild_join not guild_id
vale wing
#

Or what is that

slate swan
#

0, 30

vale wing
#

Oh

#

Anyway what does it mean

slate swan
naive dew
#

i want make a bot on node.js

vale wing
#

Ok

paper sluice
naive dew
#

thx @slate swan

slate swan
vale wing
#

Why not just LIMIT 30

slate swan
#

idk why they do that, the viewer had it by default :p

slate swan
#

they have paginator which moves on to 30, 60 on the next page

slate swan
robust fulcrum
#

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()
slate swan
#
cursor = connection.cursor()
    await cursor.execute('INSERT INTO prefixtable VALUES ( ? , "@")',(id,))``` await connection.cursor when
robust fulcrum
#

Do we need to?

slate swan
#

yes

robust fulcrum
slate swan
#

gg, so your custom prefix system works now?

robust fulcrum
#

Ye

paper sluice
#

πŸŽ‰

robust fulcrum
#

😴

#

I need to add it in my main bot now

slate swan
#

πŸŽ‰ nice, now find a way to default a prefix if your bot was invited while the bot was offline

robust fulcrum
#

Head ache

robust fulcrum
slate swan
#

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

flat solstice
#

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)

slate swan
#

is that a string?

flat solstice
#

Facepalm 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

slate swan
#

indeed. getenv always gives you a str iirc

#

!d os.getenv

unkempt canyonBOT
#

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.
slate swan
#

key, default and the result are str.

robust fulcrum
slate swan
slate swan
#

*without

#

faster I am

#

ty for correcting me

#

indeed

#

human you are, cant compete me

boreal ravine
#

I wonder why it doesn't have an underscore πŸ€” maybe because it was ported from another language?

maiden fable
#

Probably

covert basin
#
@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?

boreal ravine
boreal ravine
paper sluice
boreal ravine
covert basin
#

Is this the token?

slate swan
#

Yeah it's not the client secret

shrewd apex
#

nope

slate swan
#

Go to the bot page, copy the bot token

shrewd apex
#

token is visible only once when u create the application

slate swan
#

Actually regenerate to copy it

shrewd apex
#

after that u have to reset and copy

robust fulcrum
# slate swan yes, first try getting the prefix for that server using the code you in the get_...
@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?

slate swan
#

exactly !

robust fulcrum
slate swan
#

mhhh

dusky pine
#

probably replace check == None with check is None

slate swan
#

Lots of redundant code

#

yes the await ctx.send and connection. commit can be moved out of the if/else

robust fulcrum
dusky pine
unkempt canyonBOT
#
is

6.10.3. Identity comparisons

The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. 4

slate swan
#
id = ctx.message.guild.id
    connection = ctx.bot.connection
    cursor = await connection.cursor()``` and these var
dusky pine
#

prefer using is for comparing with singletons

slate swan
robust fulcrum
#

@slate swan

#

Can I put these prefix thing in cogs?

slate swan
#

ofcourse.

robust fulcrum
#

I confused how to

slate swan
#

just like any other command...

robust fulcrum
#

Do i need to import that?

#

Like
from main import bot.connection?

slate swan
#

nope

#

you can always access the connection using ctx.bot.connection

robust fulcrum
#

Oh k

paper sluice
robust fulcrum
slate swan
#

doesnt really matter but sure

#

i prefer not doing that

robust fulcrum
#

Do event name is on_guild_remove?

slate swan
#

yes

slate swan
covert basin
robust fulcrum
slate swan
#

no

slate swan
#

barely seems to exist

robust fulcrum
#

I will amke economy too

#

So storage matters

slate swan
#

dont

robust fulcrum
#

Replit gives only 1 gb sadly

slate swan
#

;-;

#

1 gb, that you cant utilise.

shrewd apex
#

1gb is more than enough

robust fulcrum
#

Ik

slate swan
#

it's not 10 records will fill up a gb

#

cause they will just purge your files since their file system is ephemeral

robust fulcrum
#

My bot is already 89 mb

slate swan
#

"89"

paper sluice
#

bruh one row with two columns takes like 64 bytes

paper sluice
#

probably less depending on the data type

robust fulcrum
#

But i would prefer deleting

slate swan
paper sluice
robust fulcrum
#

64 byte also precious

slate swan
slate swan
robust fulcrum
#

Whats pychache

slate swan
#

reminds me of the goblin πŸ˜”

paper sluice
slate swan
robust fulcrum
#

I dint like waste stuff in my bot

#

Clean bot

#

Clean and green

slate swan
#

green

robust fulcrum
#

Clean and python

slate swan
#

ew

paper sluice
#

you are better of optimizing ur python code than sql for space optimizations

dusky pine
#

haha people care about n bytes in code

#

my docstrings will probably take up 20%

#

just ask

slate swan
#

@robust fulcrum my db file with 10000 guild, prefix items takes 156 kb

robust fulcrum
#

How to delete the prefix and guild I'd from db?

robust fulcrum
dusky pine
#

oh yeah delete

#

delete is for rows i forgot

slate swan
paper sluice
#

DELETE ...;DROP table πŸ’€

slate swan
#

make him drop the complete table

dusky pine
#

Me rn doing !set_prefix @'; DROP TABLE prefixtable;--

robust fulcrum
#

I confused

dusky pine
#

can't forget the classic ;--

slate swan
robust fulcrum
#

Hmm what should I do now

covert basin
paper sluice
#

put the command inside the cog class

robust fulcrum
slate swan
shrewd apex
#

self, interaction

slate swan
#

they provide a ApplicationContext or something class as the first arg instead of interaction

robust fulcrum
slate swan
robust fulcrum
slate swan
#

yep

robust fulcrum
#

I thought only 1

slate swan
#

it deletes both

shrewd apex
#

it deletes the whole row

slate swan
#

uwu

robust fulcrum
#

@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?

lament mesa
#

you can make a separate script to delete the rows in the db which the bot is not in

slate swan
#

when making a ticket bot, how do you set the permissions for it?

dusky pine
robust fulcrum
dusky pine
#

You can make a script to check if the bot is not in that server

robust fulcrum
#

Hard for me

slate swan
#

when making a ticket bot, how do you set the permissions for it?

hushed galleon
#

permissions for the bot itself, or the created tickets?

open gust
#

how can i copy a message one channel to another channel?

paper sluice
open gust
#

which command i mean.

paper sluice
#

which message do you want to send to another channel?

slate swan
hushed galleon
# slate swan 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

slate swan
hushed galleon
#

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, ...)

slate swan
#

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

vale wing
#

create_text_channel returns channel object

slate swan
#

yeah ik that

quaint epoch
vale wing
#

And you can't send an ephemeral without interaction if you meant that

quaint epoch
shadow vigil
vocal snow
# shadow vigil 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...

β–Ά Play video
pliant pagoda
#
@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?

crimson pendant
#

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

hushed galleon
pliant pagoda
#

thank youπŸ™‚

vale spear
#

hey is there any good tutorial on discord.py library?

slate swan
unkempt canyonBOT
pliant pagoda
#
@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🧐

vocal snow
slate swan
swift pumice
#
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
slate swan
#

anyone know how to delete a channel through interaction?

swift pumice
pliant pagoda
#

Β―_(ツ)_/Β―

#

the role adding part works

vocal snow
swift pumice
#

could u maybe help me with my problem?

vocal snow
slate swan
#

See

vocal snow
#

commands.Context

slate swan
#

Uh

#

Discord.ext

#

I forgot

vocal snow
#

wAHT

slate swan
#

Ye

swift pumice
#

what

pliant pagoda
swift pumice
# pliant pagoda ``` @bot.command(pass_context=True) async def verify(ctx): MEMBER = discord....
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
swift pumice
#

should i rather use discord?

#

i only use nextcord because a friend said to me nextcord is better

vocal snow
#

That's upto preference but I'm not familiar with nextcord. I'll need to check out their docs

slate swan
swift pumice
slate swan
ivory owl
#

is there a delete command similar to attachments.save?

grim oar
#

Delete from disk or delete the attachment message

slate swan
#

how do i delete a channel thru an interaction? im trying to freshen up my ticket system.

grim oar
#

!d discord.Interaction.channel

unkempt canyonBOT
grim oar
#

!d discord.TextChannel.delete

unkempt canyonBOT
#

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.
ivory owl
#

because it messes if I use the command again and produces two juxtaposed images

pliant pagoda
#
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?

rare saddle
#

How to get a channel's webhook and send a message through it

paper sluice
pliant pagoda
#

Nevermind not figured it out

vocal snow
paper sluice
rare saddle
#

How to get webhook by url

vocal snow
unkempt canyonBOT
#

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`.
rare saddle
paper sluice
#

its from_url not url

rare saddle
#

vs code

sick birch
rare saddle
paper sluice
vocal snow
pliant pagoda
# sick birch Save the random number to a variable

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?

paper sluice
paper sluice
pliant pagoda
#

thank you

sick birch
pliant pagoda
paper sluice
pliant pagoda
#

🧐

#

im not sure how to do that sorry

paper sluice
#

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 )

slate swan
#

πŸ‘€

paper sluice
vale sierra
#

whats is the code to have the bot avatar ? please

paper sluice
#

you didnt pass the message parameter

vale sierra
#

bot.avatar.url ?

paper sluice
#

oh, you want to use events in cogs, for that you need to decorate it with @commands.Cog.listener()

paper sluice
vale sierra
iron sorrel
#
@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

paper sluice
#

because you are sending the message in message.channel not create_channel

iron sorrel
paper sluice
#

I'm confused, are you looking for autocorrect suggestions?

iron sorrel
#

auto-what 😭😭 yes yes im looking for those

slate swan
#

Hi

paper sluice
#

no, i don't think you want that check, just do create_channel.send(message)

paper sluice