#discord-bots

1 messages ยท Page 1139 of 1

loud junco
#

๐Ÿ‘€

lavish shadow
#

yo guys, im trying to add a button to my discord embed in .py
how should i do it? couldnt find anything on the docs

paper sluice
unkempt canyonBOT
#

class discord.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
paper sluice
#

like this:

...
view = discord.ui.View()
view.add_item(discord.ui.Button(...))
ctx.send(embed=embed, view=view)
robust fulcrum
#

?

shrewd apex
#

why would u create a database for prefixes

#

just create one db and create a prefix table in thatpithink

slate swan
#

^

#

and connecting every time...

robust fulcrum
#

How to fix this?

slate swan
#

f

robust fulcrum
#

.

shrewd apex
#

rip

robust fulcrum
#

Ig i did something silly wrong

slate swan
#

even the sql operations are wrong, I think i'll create an example for custom prefixes

robust fulcrum
shrewd apex
#

almost the whole thing

robust fulcrum
#

Tf

shrewd apex
#

ur approach of using db is wrong

robust fulcrum
#

Hmmm

#

How can I make it good?

shrewd apex
#

a database is a database coz it can store multiple stuff

#

u don't make one db for each thing instead u make one db and store everything there

robust fulcrum
#

I made one db bro

shrewd apex
#

for starters u can make ur table in the setup hook itself with the create table statement and then make a db connection object and use that connection throughout the bot

#

instead of opening and closing everytime

robust fulcrum
#

Oh means i should do
setup_hook() where i need to connect?

shrewd apex
#

do u open and close the door of ur room everytime i enter or exit ๐Ÿ‘€ same principle

shrewd apex
robust fulcrum
#

Ok

shrewd apex
#

u can even make a .py file for all SQL db and tables and run that function in the setup hook

shrewd apex
slate swan
robust fulcrum
shrewd apex
#

wait ashley is writing a tutorial

supple thorn
robust fulcrum
#
import aiosqlite
import discord
from discord.ext import commands
import asyncio

async def connection():
    bot.connect = await aiosqlite.connect('prefixes.db')
    cursor = await bot.connect.cursor()
    await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtab(guild_id INTEGER,prefix TEXT)')
    await bot.connect.commit()
    await bot.connect.close()

async def get_prefix(Bot, message):
    id = message.guild.id
    await bot.cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',{id})
    prefix = await bot.cursor.fetchone()
    if prefix:
        return prefix
    else:
        return '~'
    await connect.commit()

bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())

bot.setup_hook = connection

@bot.event
async def on_ready():
    print("ready")

@bot.command()
async def test(ctx):
    await ctx.send("working")

@shrewd apex

robust fulcrum
#

Is it correct now.

slate swan
#

I literally made a custom prefix shit in 5 minutes and it works

robust fulcrum
#

You pro

slate swan
#

no

shrewd apex
#

nais Ashley help him

#

or post as gist

#

one more pinned message

robust fulcrum
#

๐Ÿ˜ตโ€๐Ÿ’ซ

#

I really a noob

slate swan
#

people either use their brains or leave it

robust fulcrum
#

My brain is 10%

shrewd apex
#

same as Einstein's ๐Ÿ‘€

robust fulcrum
#

Bruh

shrewd apex
#

theoretically Einstein's used 10% of his brain

#

avg people like me 1%

#

barely

robust fulcrum
#

Me very less brain

#

๐Ÿง 
๐Ÿ”ฅ

#

My Brain buring

paper sluice
paper sluice
robust fulcrum
#

Me use 1% in playing games

#

And 5% study

#

And 0.1% python

paper sluice
#

good boy

#

or girl, idk

robust fulcrum
#

โ™‚๏ธ

slate swan
shrewd apex
#

my brain usage chart
.5% python
.4.9% other stuff
.01% study

paper sluice
robust fulcrum
slate swan
#

I'm high

robust fulcrum
#

๐Ÿ˜ฉ

paper sluice
# slate swan I'm high

i was watching like a 4 part documentary on basketball players being high and taking pills to lower down b4 games

#

in the 1980s*

robust fulcrum
#

@shrewd apex do you have yt ch?

shrewd apex
#

no

robust fulcrum
shrewd apex
paper sluice
#

finally got this working ( again )

robust fulcrum
#

Me watch python tut but learn nothing

slate swan
#

nice none of my message commands work...

paper sluice
paper sluice
slate swan
#

helpp ๐Ÿ˜ญ

slate swan
#

๐Ÿ˜”

robust fulcrum
#

Me watch 2hrs

paper sluice
robust fulcrum
#

๐Ÿ˜‚

robust fulcrum
slate swan
robust fulcrum
#

I not got glasses yet

paper sluice
#

i need glasses, but i wont get em ๐Ÿ˜Ž

robust fulcrum
#

Wearnung glasses is like a dare

slate swan
robust fulcrum
#

๐Ÿท

robust fulcrum
#

I bored

slate swan
#

sleep

robust fulcrum
#

I already slept a lot

slate swan
#

cry

robust fulcrum
#

Hmm for what reason

paper sluice
#

aint no tears left to cry

robust fulcrum
#

Ig i should cry for python

slate swan
#

๐Ÿ’€ just dont apply that statement to wrong stuff pliz

robust fulcrum
paper sluice
robust fulcrum
#

Anyone here have any tutorial on sqlite?

paper sluice
robust fulcrum
lament mesa
#

there probably aren't tutorials for using sqlite in discord bots

#

seems too specific

shrewd apex
#

i know one for pgsql

#

idk for aiosqlite

#

but the pgsql one is kinda well not too pro

paper sluice
lament mesa
#

any errors?

shrewd apex
lament mesa
slate swan
#

get glasses

shrewd apex
#

lmao

lament mesa
#

no

slate swan
#

that code doesnt even make sense

shrewd apex
#

^^

slate swan
#

just like our lives....

lament mesa
#

idk dude ยฏ_(ใƒ„)_/ยฏ

robust fulcrum
lament mesa
robust fulcrum
robust fulcrum
#
import aiosqlite
import discord
from discord.ext import commands
import asyncio

async def get_prefix(Bot, message):
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    id = message.guild.id
    await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',{id})
    await connect.commit()
    prefix = await cursor.fetchone()
    if prefix:
        return prefix
    else:
        return '~'
    await connect.commit()
    await connect.close()

bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())

async def connect():
    bot.connect = await aiosqlite.connect('prefixes.db')
    cursor = await bot.connect.cursor()
    await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtab(guild_id INTEGER,prefix TEXT)')
    await bot.connect.commit()
    await bot.connect.close()

bot.setup_hook = connect

@bot.event
async def on_ready():
    print("ready")

@bot.command()
async def test(ctx):
    await ctx.send("working")
lament mesa
# robust fulcrum

try py await bot.cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
use a tuple instead of a set

#

and also what is this new setup hook thing thinkmon

shrewd apex
lament mesa
#

you forgot the comma, it should be (id,) not (id),

lament mesa
robust fulcrum
#

It's working

#

Uuuu maaaaa

lament mesa
#

๐Ÿ‘

robust fulcrum
#

Now i need to make the set_prefix

robust fulcrum
lament mesa
#

there was a mentions_or function iirc

shrewd apex
#

when_mentioned_or

lament mesa
shrewd apex
#

!d discord.ext.commands.when_mentioned_or

unkempt canyonBOT
#

discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.

These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.

Example

```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
shrewd apex
#

...

robust fulcrum
#

?

shrewd apex
#

(get_prefix)

#

its a function call it

shrewd apex
#

commands.when_mentioned_or(get_prefix)

robust fulcrum
robust fulcrum
shrewd apex
#

return the prefix from get_prefix function

robust fulcrum
#

I returning

robust fulcrum
# shrewd apex return the prefix from get_prefix function
async def get_prefix(Bot, message):
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    id = message.guild.id
    await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
    await connect.commit()
    prefix = await cursor.fetchone()
    if prefix:
        return prefix
    else:
        return '~'
    await connect.commit()
    await connect.close()
shrewd apex
#

tell me if u are returning how is the commit and close working

iron sorrel
robust fulcrum
#

Prefix table empty yet

shrewd apex
#

also if u are just reading from db do u need commit?

#

i dont think so

robust fulcrum
#

Hmm

#

Ig for selecting value

iron sorrel
#

why do u need the bot parameter in this function

#

you are not even using it

robust fulcrum
#

Someone told me

lament mesa
#

bot will be passed if you use it or not

robust fulcrum
#

How can we update the cell in sqlite?

#

Means i want to update the prefix where guild Id is message guild id

iron sorrel
#
UPDATE table
SET 
  column=?
WHERE guild_id=?
robust fulcrum
iron sorrel
#

no

#

not any, you would rather do NULL

#

and then while fetching your data, you will do:
prefix = curs.fetchone() or "!"

#

null or default is gonna be default

#

some or default is gonna be some

robust fulcrum
# iron sorrel no
await cursor.execute('UPDATE prefixtab SET prefix=? WHERE guild_id=?',(newpre,id))

I made for updating prefix

robust fulcrum
#

How can I fix it?

#

Pls help

#

๐Ÿฅบ

paper sluice
flat solstice
#

Is it possible to use a mix of the new auto mod features and modals to present users with a yes/no question when they try to send a msg? For example I want to try to display a 'popup' to user's when they try to send a msg that includes a ping to one of my staff members so that I can ask them why they are attempting to ping that person (in our rules we don't allow ppl to ping for support issues but they can ping for moderation issues and I want them to confirm they understand that rule before sending their msg). If it's not possible right now do you think it will be possible in future as discord expands on the auto mod API

robust fulcrum
robust fulcrum
junior forum
#

will i recieve help for webhooks here?

#

discord webhooks

slow fog
#

what is it

junior forum
#

So i made this code that scrapes a website

#

and then whenevr there is an event on the website, it is supposed to notify in the embed

junior forum
# slow fog what is it

But when i run the code and when there is an event, it doesnt send the message however it logs it on heroku(host)

slow fog
#

oh

#

can i see the code or any other details

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)
          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)```
#

@slow fog

slow fog
#

oh well that sounds complicated a bit for me i havent dealt with any kind of web scrapping before

#

i cant help

junior forum
#

it logs it on the console

vale sierra
#
    @commands.command()
    async def inv(self, ctx):
        animal_list = [None, "๐ŸฆŠ Fox", "๐Ÿบ Wolf", "๐Ÿฑ Cat", "๐Ÿฆ Raccoon", "๐Ÿฏ Tiger", "๐Ÿฆ Lion", "๐Ÿ† Leopard", "๐ŸฆŒ Deer", "๐Ÿฆ“ Zebra", "๐Ÿฆ„ Unicorn"]
        tools_list = [None, "๐Ÿ”ซ Carabine", "๐ŸŽฃ Rod", "โ› Pickaxe"]

        db = sqlite3.connect("eco.sqlite")
        cursor = db.cursor()

        cursor.execute(f"SELECT * FROM animals WHERE user_id = {ctx.author.id}")
        animals = cursor.fetchone()

        cursor.execute(f"SELECT * FROM tools WHERE user_id = {ctx.author.id}")
        tools = cursor.fetchone()

        animals_ = [f"{i} x{j}" for i, j in itertools.zip_longest(animal_list, animals) if 0 < j < 1000000000000000000]
        tools_ = [f"{i} x{j}" for i, j in itertools.zip_longest(tools_list, tools) if 0 < j < 1000000000000000000]

        animals_ = "\n".join(animals_) if len(animals_) > 0 else "*No animals in Inventory*"
        tools_ = "\n".join(tools_) if len(tools_) > 0 else "*No tools in Inventory*"

        embed = discord.Embed(title="Inventaire", description=f"Votre stuff", color=0xec0c0c, timestamp=ctx.message.created_at)
        embed.add_field(name="Animaux", value=animals_)
        embed.add_field(name="Outils", value=tools_)

        await ctx.send(embed = embed)
``` Hello, i have this error with this code thank for helping me !
slate swan
#

hello

#

I was wondering if anyone could help me out

#

How do I start a discord bot.py

junior forum
#

my friend is using it, it works for him

slate swan
#

any YouTube tutorials recommended?

#

any youtube tutorials recommended for me to start setting up a discordbot.py

vale sierra
#

? no the error is what i send

junior forum
#

then what should i do ?

#

i dont understand

vale sierra
#

animals_ = [f"{i} x{j}" for i, j in itertools.zip_longest(animal_list, animals) if 0 < j < 1000000000000000000]
TypeError: 'NoneType' object is not iterable

slate swan
#

what library do u recommend

#

and where are the docs

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

slate swan
#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

junior forum
#

theyre using the same thing

vale sierra
#

how can i fix this ?

junior forum
#

okay... also any idea on why it logs the stuff in the console

unkempt canyonBOT
#

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

('a', 'd') ('b', 'e') ('c', 'f') (None, 'g')
vale sierra
#

the same length ?

junior forum
#

They just said its supposed to work

paper sluice
vale sierra
#

fixed the problem, thats wasnt this but thanks

robust fulcrum
robust fulcrum
paper sluice
cloud dawn
#

That point just use a Client

robust fulcrum
# paper sluice means you basically doing `command_prefix=None` in the `commands.Bot`'s construc...
import aiosqlite
import discord
from discord.ext import commands
import asyncio

async def get_prefix(Bot, message):
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    id = message.guild.id
    await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
    await connect.commit()
    prefix = await cursor.fetchone()
    print(prefix)
    return prefix
    await connect.close()

bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())

async def connect():
    bot.connect = await aiosqlite.connect('prefixes.db')
    cursor = await bot.connect.cursor()
    await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtab(guild_id INTEGER,prefix TEXT)')
    await bot.connect.commit()
    await bot.connect.close()

bot.setup_hook = connect

@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):
    id = ctx.guild.id
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
    await connect.commit()
    await cursor.execute('UPDATE prefixtab SET prefix=? WHERE guild_id=?',(newpre,id))
    await connect.commit()
    await connect.close()

Here is code any solution?

paper sluice
#
    return prefix
    await connect.close()

bruh, the connection would never close

#

do this

try:
    return prefix
finally:
    await connect.close()

or better, just use the context manager

async with aiosqlite.connect('prefixes.db') as connect:
    cursor = await connect.cursor()
     ...
     return prefix

and for your problem, prefix is None and hence why you get that error

robust fulcrum
paper sluice
#

sparky has been typing for the past 30 mins

paper sluice
robust fulcrum
#

Sqlite annoying

paper sluice
robust fulcrum
#
import aiosqlite
import discord
from discord.ext import commands
import asyncio

async def get_prefix(Bot, message):
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    id = message.guild.id
    await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
    await connect.commit()
    prefix = await cursor.fetchone()
    try:
        print(prefix)
        return prefix
    finally:
        await connect.close()

bot = commands.Bot(command_prefix=get_prefix, intents=discord.Intents.all())

async def connect():
    bot.connect = await aiosqlite.connect('prefixes.db')
    cursor = await bot.connect.cursor()
    await cursor.execute('CREATE TABLE IF NOT EXISTS prefixtab(guild_id INTEGER,prefix TEXT)')
    await bot.connect.commit()
    await bot.connect.close()

bot.setup_hook = connect

@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):
    id = ctx.guild.id
    connect = await aiosqlite.connect('prefixes.db')
    cursor = await connect.cursor()
    await cursor.execute('SELECT prefix FROM prefixtab where guild_id=?',(id,))
    await connect.commit()
    await cursor.execute('UPDATE prefixtab SET prefix=? WHERE guild_id=?',(newpre,id))
    await connect.commit()
    await connect.close()
slate swan
paper sluice
paper sluice
winter gull
#

What would be a good way for file structure for a discord bot? I am currently using this

#

check out the discord-bot-hosting thread

paper sluice
paper sluice
#

cogs? files with functions you use in ur code?

winter gull
winter gull
slate swan
#

hi guys, can someone help me wit my bot, i want to save the authors message, but i cant

winter gull
#

save it where?

paper sluice
winter gull
#

oh, then what about .env file?

slate swan
paper sluice
winter gull
paper sluice
slate swan
winter gull
slate swan
#

@winter gullYou wrote: <Message id=994612427494801468 channel=<TextChannel id=989187476264452176 name='ad' position=0 nsfw=False news=False category_id=988838505515978853> type=<MessageType.default: 0> author=<Member id=988836454056755200 name='EventCasino' discriminator='5254' bot=True nick=None guild=<Guild id=988838505515978852 name='ะกะตั€ะฒะตั€ MError' shard_id=None chunked=True member_count=2>> flags=<MessageFlags value=64>> thats what i got

#

test.content

winter gull
slate swan
#

@winter gull if im working with TEST, i want to make it smaller for exampler, im working with my thue message, right?

worn lintel
#
def speak(text): 
    textas = gTTS(text=text, lang="en", slow=False)
    filename = "sir.mp3"
    textas.save(filename)


@client.command()
async def talk(ctx,*, text):
  speak(text)
  await ctx.send(file=File("sir.mp3"))```
#

just bored

paper sluice
#

sad /tts noises

slate swan
#

๐Ÿ’€

winter gull
slate swan
covert basin
#
@client.command()
async def meme(ctx, meme_id):
  meme_library = {
    "yeet": f'https://i.ibb.co/Fqm1gcY/ezgif-1-25675fbeab.gif',
    "simp": f'https://i.ibb.co/NKdb93v/simp-pointing.gif',
    "hagay": f'https://i.ibb.co/9HHjgpF/giphy-1.gif',
}

  embed=discord.Embed(
    title=f'{meme_id}',
description=f'',
    color=discord.Color.purple()
  )

  no_meme=discord.Embed(
    title=f'No such meme in my harddisk ๐Ÿ˜ญ',
description=f'',
    color=discord.Color.purple()
  )
  embed.set_image(url=f'{meme_library[meme_id]}')
  if meme_id in meme_library:
    await ctx.send(embed=embed)
  else:
    await ctx.send(no_meme=no_meme)

I want to set if there is no meme in the dictionary, the bot will reply with "No such meme in my harddisk ๐Ÿ˜ญ", but it doesn't work, what is the problem in my code

#
  if meme_id in meme_library:
    await ctx.send(embed=embed)
  else:
    await ctx.send(no_meme=no_meme)

I think the main problem is in here

paper sluice
#

bro do embed=no_meme

slate swan
#

๐Ÿ’€

#

no_meme=no_meme

covert basin
paper sluice
#

description can't be empty

#

so add ** **, or _ _

slate swan
#

how can i work with test as a string ?
test = await client.wait_for('message')
sss = test[0]
await ctx.send(f"You wrote: {sss.content}")

slate swan
covert basin
vale wing
#

Just remove the description if it's empty also f'' wtf

#

If you use f-string, use it

paper sluice
vale wing
#

Otherwise use normal string

slate swan
#

how can i work with test as a string ?
test = await client.wait_for('message')
sss = test[0]
await ctx.send(f"first sign you wrote: {sss.content}")

pls help meee

slate swan
paper sluice
#

cool

slate swan
#

In fields u need both

#

Help

#

Ye?

#

My code wont work

#

Sad

#

It gives me a bunch of errors

#

help me guys

#

Ok both post errors

#
import discord
import random

TOKEN = 'no u cant see this'
client = discord.Client()

@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

@client.event
async def on_message():
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.author == client.user:
        return

    if message.channel.name == 'general':
        if user_message.lowercase() == 'hello':
            await message.channel.send(f'Hello {username}!')
            return
        elif user_message.lower() == 'bye':
            await message.channel.send(f'See you later {username}!')
            return
        elif user_message.lower() == '!random':
            response = f'Your rnadom number is: {random.randint(1, 100)}'
            await message.channel.send(response)
            return

    if user_message.lower() == '!anywhere':
        await message.channel.send('This can be used anywhere!')
        return

client.run(TOKEN)
#

Wont work

vale wing
tough lance
#

Hi

covert basin
#

Still not working

slate swan
#

it gives me a bunch of errors

#

It says Unsolved Reference

#

Whenever the message comes up

vale wing
vale wing
#

Find a tutorial that teaches about using @bot.command decorator

slate swan
#

so what do I change? I was just following a youtube tutorial

slate swan
#

In this video I'll be showing you how you can create a very easy Discord Chat Bot that can do cool things on your Server using Python. Check out: @Pythonize for more epic Python content!

00:00 Intro
01:08 Discord Developer Portal
04:39 Adding the Bot to the server
06:16 Adding responses
11:16 Running the Bot

Latest updates:
โžญ https://twitter....

โ–ถ Play video
slate swan
#

That one

vale wing
slate swan
#

test = await client.wait_for('message')
sss = test[0].content
await ctx.send(f"You wrote: {sss}")

#

It also gives me an error

#

when I do bot.command

#

it says unsolved reference

#

Bro

vale wing
slate swan
#

Okay

#

THen what do I do

#

Can any of u give me a youtube tutorial to follow?

slate swan
#

Okay

vale wing
#

I have one in my repo but it's unfinished

slate swan
#

@vale wing whats wrong?
test = await client.wait_for('message')
sss = test[0].content
await ctx.send(f"You wrote: {sss}")

#

Cant find a tutorial on it lol

#

is there the docs

vale wing
#

test[0].content, the message is not subscriptable unlike content

slate swan
#

that could show it

#

!d discord

unkempt canyonBOT
#

In order to work with the library and the Discord API in general, we must first create a Discord Bot account.

Creating a Bot account is a pretty straightforward process.

vale wing
#

!d discord.ext.commands.Bot.command

unkempt canyonBOT
#

@command(*args, **kwargs)```
A shortcut decorator that invokes [`command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") and adds it to the internal command list via [`add_command()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin.add_command "discord.ext.commands.GroupMixin.add_command").
slate swan
#

Hello, how can I fix this error?

vale wing
#

And I think there's a good example but somewhere else

vale wing
slate swan
#

lol

tough lance
slate swan
#

so how can i work with test as a string?

slate swan
vale wing
#

Discord

slate swan
#

ur using 1.7.3

#

okay thanks

slate swan
slate swan
vale wing
#

I already told you

#

Ask someone else if my explanation wasn't clear, I am not a spoonfeeder

tough lance
slate swan
vale wing
#

Ok "clearer" explanation: the test is an instance of discord.Message, you want its content. Content is accessible with content attribute of discord.Message object. Attribute is a programming term you should be familiar with

#

Looks even more confusing

flat fiber
#

how i can put my bot to answer a word and not exactly all the prashe

#

i can provide my code if you want to see but idk how to put only just a word required and notall the phrase

tough lance
#

Wdym?

flat fiber
#

look

#

when i write hi the bot answer hi too

slate swan
#

im too bad

flat fiber
#

but when i write hi bot he doesnt answer

slate swan
#

pip install -U git+https://github.com/Rapptz/discord.py

tough lance
vale wing
winter gull
slate swan
vale wing
#

You can't work with Message as a string cause it's not one

tough lance
slate swan
#

๐Ÿ‘€

vale wing
#

You can only work with its content which you most likely need

vale wing
flat fiber
vale wing
#

Wut

flat fiber
#

mate i am confused as fuck

vale wing
#

!e print("hi" in "hi dude")

unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

True
slate swan
#

ha yes it's true I had forgotten

#

thanks

vale wing
#

You basically get a bool from that

slate swan
vale wing
#

test is not a str

slate swan
vale wing
#

May I ask

#

What's your python knowledge

slate swan
#

L

vale wing
#

Nice

#

Who was I even explaining OOP to

slate swan
#

MError

slate swan
vale wing
#

Ok I encourage learning but learning python from a discord bot is not a good idea with zero of python knowledge

vale wing
slate swan
#

Cool

vale wing
#

That's truly cool but you should learn about OOP for python

#

Object oriented programming

slate swan
#

just explane me how make test.message to test.string

#

to_string

vale wing
#

Eh I didn't want to do this till the last moment

#

test.content

#

Ok now I am a spoonfeeder ๐Ÿ˜”

slate swan
#

Haha

#

my eng is 0, my python is 0, and your jokes are ununderstandable

#

๐Ÿ’€

#

gor me

vale wing
#

He's joking about me but ok

slate swan
flint isle
#

ive been working on a command that will re encode a video and i got the encoder working but im running into the issue of this error

Waiting For Commands
WARNING:disnake.gateway:Shard ID None heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 51, in <module>
    bot.load_extension('cogs.events')
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\common_bot_base.py", line 487, in load_extension
    self._load_from_module_spec(spec, name)
vale wing
#

No way my AI bot got 3 stars on repo, that's the max I have ever reached lmao

vale wing
#

Although I can't tell exactly

#

But seems like it is

#

Run your encoding process in executor

#

I don't remember its name

slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object is not callable new mistake guys

vale wing
#

Basically asyncio.get_event_loop().run_in_executor(None, your_func)

slate swan
#

progress incoming

#

there is always a mistake

#

Don't call

#

Event

#

How do I call it to make it work?

vale wing
#

You don't

#

You decorate a func with it, the decorator doesn't require arguments actually ๐Ÿค“

slate swan
#

im trying this:

test = await client.wait_for('message')
sss=test.content[0]
await ctx.send(f"You wrote: {sss}")

#

Nice

slate swan
# slate swan Nice

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: string index out of range

#

not nice(

#

Ok im done

#

just remove [0] and ur fine

#

sorry it's enough

#

if i need only first sign ?

lament depotBOT
#
You're bad at computers.

@sick panther, please enable your DMs to receive the bookmark.

slate swan
#

Lol

tawdry canyon
#

please can someone help me with discord.py

I keep getting the same error:
AttributeError: 'Client' object has no attribute 'guild'

Here is my code:
`import discord
from datetime import datetime

client = discord.Client()

@client.event
async def on_ready():
print("Ready")
print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
if message.author == client.user:
return

quotes_channel_id = discord.utils.get(client.guild.channels, name="quotes").id
bot_message = f"{message}\n- {message.author}, {datetime.today().strftime('%d/%m/%Y')}"
await quotes_channel_id.send(bot_message)
print(f"{bot_message}")

client.run('bot token')`

paper sluice
paper sluice
tawdry canyon
#

tysm

slate swan
tawdry canyon
paper sluice
#

remove the .id

tawdry canyon
#

oh ok

paper sluice
slate swan
night lagoon
#

I do my own library, and it loads my font from bot files, not from library files

#

How to fix this?

#

I try it and this is not working

font_path = os.path.join(os.path.dirname(__file__), "SFMono.ttf")

my_font = Font(font_path, size=40)โ€Š```
slate swan
#

Hello

#

I was wondering why this code isnt working

@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

    channel1 = client.get_channel(994603594814849067)
    await channel1.send('Hello I am back online now.')

    user = client.get_user(756857769545564180)
    await user.send('Yo whats good kid.')```
#

The last two lines of the code dont work

#

It is supposed to send a direct message to me.

paper sluice
iron sorrel
#

can i make a task run every hour? like not looping in an hour, every
00:00 AM 01:00 AM ... 12:00 PM so on

#

you arent reading, are you?

slate swan
winter gull
#

it showed up after sometime running the bot

slate swan
#

wym by thatr

iron sorrel
#

actually, fetching users in on ready is a bad idea, cuz thats just how discord api is built

iron sorrel
# slate swan wym by thatr

bots have caches, of users and so on, when you connect to discord api, they send you that cache, and you can access it later,

tough lance
unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
winter gull
iron sorrel
tough lance
iron sorrel
#

no, listen

tough lance
#

Time Param makes the loop run at specific intervals

winter gull
#
@bot.listen()
async def on_ready():
    bot.loop.create_task(dynamic_presence())

async def dynamic_presence():
    while True:
        await bot.change_presence(activity=discord.Game(name=f"with {JavaServer.lookup('').status().players.online} players on "))

the error popped when i wrote this code

iron sorrel
#

i dont want to run a task each hour, i want to run a task each time the clock hits 00 minutes, each time an hour passes FROM 00:00, AND NOT from the time the task was started

iron sorrel
tough lance
#

I mean it rakes datetime.time as parm

iron sorrel
iron sorrel
tough lance
iron sorrel
#

show me how I run a task at 12:00pm and 12:00 am

#

ok

#

thank you so much<3

paper sluice
vale wing
flint isle
vale wing
#

You can specify some other if you would like to

slate swan
#
    @commands.command()
    @commands.guild_only()
    @commands.cooldown(1, 10, commands.BucketType.user)
    async def help(self, ctx):
        await ctx.send("Pick now!!", components = [Select(placeholder="Options", options=[SelectOption(label="Monkey", value="Ok")])])
        interaction = await self.client.wait_for("select_option", check = lambda i: i.component[0].value == "Ok")
        print('Hi!')

Doesnt work it always says interaction failed catRage

vale wing
#

Default one works fine imo

vale wing
slate swan
#

ok

vale wing
#

Also help is a builtin

zinc reef
#

you can ovewrite anything in python

In [1]: help = "hi mom"

In [2]: help
Out[2]: 'hi mom'
#

it's just not a good practice

paper sluice
vale wing
#

Weird how people face issues with overriding it exclusively in dpy

#

Anyway overriding builtins is a bad idea generally

#

Except of course

#

id

flint isle
slate swan
#
@commands.slash_command(name='clear', description='Clear messages')
    async def clear(self, ctx: disnake.ApplicationCommandInteraction , amount=None):
        if ctx.permissions.manage_messages :
                await ctx.channel.purge(limit=amount)
        else :
            await ctx.send("no")

error - Command raised an exception: TypeError: '>' not supported between instances of 'str' and 'int'

paper sluice
#

type hint amount with int

slate swan
gusty shard
#

should i do cogs my bot?

#

will it affect anything?

slate swan
paper sluice
slate swan
slate swan
slate swan
paper sluice
gusty shard
slate swan
paper sluice
#

amount: int is a type hint

#

do that ^

slate swan
pine marsh
#

anyone wanna help?? got a discord bot that is auto posting embeds to twitter via tweepy.. i can get it to work with message.content but i need embed description and image... ive tried a few things but caint get it, heres my code below

if message.author != client.user and str(message.channel.id) ==discord_channel_id3 :
        api.update_status(status=message.content)
        print('Tweet posted from channel 3')

this is the part i need help with

       api.update_status(status=message.content)

assuming its gotta be something like this?

       api.update_status(status=message.Embed(description, image_url)

but i caint figure it out

pine marsh
iron sorrel
#

wait some time, and fetch after some time

#

im sorry if that came out rude.

limpid thicket
#

How can I await my function after the bot has finished playing the source?

voiceClient.play(source, after=await after_audio_finished)

This doesn't work.

iron sorrel
#

no, they also give you commands.task(time=) kw param, which was what i needed.

shrewd apex
#

!d discord.ext.commands.Bot.wait_until_ready

iron sorrel
unkempt canyonBOT
#

await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits until the clientโ€™s internal cache is all ready.

Warning

Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.setup_hook "discord.ext.commands.Bot.setup_hook") can lead to a deadlock.
limpid thicket
iron sorrel
heady sluice
#

music bot

iron sorrel
#

this is what i mean

slate swan
limpid thicket
#

But it says I have to await it

iron sorrel
#

await what?

limpid thicket
#

If it's after=after_play it isn't being awaited the function

#

It's an async function

iron sorrel
slate swan
#

okay

#

tysm

limpid thicket
#

You did def not async def like I did

shrewd apex
iron sorrel
iron sorrel
limpid thicket
#

ok

#

No it isnt

iron sorrel
#

there are 2 separate funcs

#

can u

#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

limpid thicket
#

I want functions but i cant send stuff or do functions on discord without it being async

slate swan
#
@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

    channel1 = client.get_channel(994603594814849067)
    await channel1.send('Hello I am back online now.')

    user = await client.fetch_user(756857769545564180)
    await user.send('Yo whats good kid.')

client.run(TOKEN)
#

This gives a RuntimeWarning: couroutine 'sleep' was never awaited

iron sorrel
#

you need to await asyncio.sleep

slate swan
#

Ok

iron sorrel
#

but where do you have asyncio sleep here, you dont have it

slate swan
#

I got rid of it

heady sluice
#

interesting

slate swan
#

It was above the line that declared user

slate swan
iron sorrel
#

and not .format,

#

.format is old, and its used for something else now,

limpid thicket
iron sorrel
#

yes

limpid thicket
#

ok they are closed

iron sorrel
#

friend request sent

slate swan
#

Why is the error message for this command not working? I have another command, it is with the same code and it is working

#
if isinstance(error, MissingPermissions):
   print("Erro.")```
#

Error is spelled wrong

slate swan
#

n vm

#

I live in Portugal

#

I just put "error" by showing in the console to see if it would show up. But it doesn't show up. A message was supposed to appear in the chat, but it doesn't appear either. It just shows the error on the console saying that the user doesn't have permission

#

yea ima be honesddt idk anythin about discord.oy yet

#

im trying to learn struff rn

slate swan
# slate swan huh? wdym?

I am using the translator, so apologies if there are errors in the message.

I have 2 commands that use the same base to show the errors. When the person does not have permission to use a command, a message should appear in the chat saying that the person does not have permission.

In command 1, it works. It shows the message that the person doesn't have permission.
On command 2, it doesn't work. It doesn't show the message.

I wanted to understand why this happens if the two commands are the same.

left idol
#

if i have a previously defined function, can i use it inside of my command function?

slate swan
slate swan
#

but for some reason, it doesn't show up in chat and neither does the print("error") I tried

#

but in command 1, he already appears in the chat

slate swan
#

can u dm?

#
# Error from Command 1 -
@banUser.error
    async def ban_error(self, ctx, error: CommandError):
        if isinstance(error, MissingPermissions):
            await ctx.send(":off:  **| Vocรช nรฃo tem permissรฃo para usar este comando!**\nPara usar este comando, vocรช precisa da permissรฃo de `Banir membros`.")```
#

so im making a welcome image that will send an image with like a little circle but i dont get any errors just nothing hppens

#
# Error from command 2 -
 @suggestionCommand.error
 async def suggestionCommand_error(self, ctx, error: CommandError):
     if isinstance(error, MissingPermissions):
        print("Erro.")
#

Amazingly, command 2, has another type of error which is "MissingRequiredArgument" and this one works perfectly.

#

@slate swan

paper sluice
slate swan
#

i dont think no

slate swan
paper sluice
#

then do intents.message_content = True before passing it in commands.Bot

slate swan
#

alright will do

slate swan
#

even if I set it to send a message. It doesn't send

#

not even the message that I tell him to put in the console he sends

paper sluice
paper sluice
slate swan
slate swan
#

i use commands.Bot my bad

vale sierra
#
@commands.command()
    async def inv(self, ctx):
        animal_list = [None, "๐ŸฆŠ Renard", "๐Ÿบ Loup", "๐Ÿฑ Chat", "๐Ÿฆ Raton-laveur", "๐Ÿฏ Tigre", "๐Ÿฆ Lion", "๐Ÿ† Lรฉopard", "๐ŸฆŒ Biche", "๐Ÿฆ“ Zรจbre", "๐Ÿฆ„ Licorne"]
        tools_list = [None, "๐Ÿ”ซ Carabine", "๐ŸŽฃ Canne ร  pรชche", "โ› Pioche"]

        db = sqlite3.connect("eco.sqlite")
        cursor = db.cursor()

        cursor.execute(f"SELECT * FROM animals WHERE user_id = {ctx.author.id}")
        animals = cursor.fetchone()

        cursor.execute(f"SELECT * FROM tools WHERE user_id = {ctx.author.id}")
        tools = cursor.fetchone()

        animals_ = [f"{i} x{j}" for i, j in itertools.zip_longest(animal_list, animals) if 0 < j < 1000000000000]
        tools_ = [f"{i} x{j}" for i, j in itertools.zip_longest(tools_list, tools) if 0 < j < 1000000000000]

        animals_ = "\n".join(animals_) if len(animals_) > 0 else "*No animals in Inventory*"
        tools_ = "\n".join(tools_) if len(tools_) > 0 else "*No tools in Inventory*"

        embed = discord.Embed(title="๐Ÿ’ผ Inventaire", description="", color=0xec0c0c, timestamp=ctx.message.created_at)
        embed.add_field(name="๐Ÿถ Animaux :", value=animals_)
        embed.add_field(name="๐Ÿ”ง Outils :", value=tools_)
        embed.set_thumbnail(url="https://cdn-icons-png.flaticon.com/512/5434/5434458.png")
        embed.set_footer(text=f"Rรฉpertoire de {ctx.author.name}", icon_url=ctx.author.avatar_url)

        await ctx.send(embed=embed)
``` Hello, i have this error with this part of code thanks for helping me
paper sluice
slate swan
#

like this?

paper sluice
slate swan
paper sluice
# slate swan like this?

no, in ur case just do client = commands.Bot(command_prefix='>>', case_insensitive=True, intents=intents)

slate swan
#

alright

paper sluice
paper sluice
slate swan
#

a group

#

ah

vale sierra
slate swan
#

there we go

#

ill try now

paper sluice
# slate swan a group

print out the type of error in the handler and see what you get when someone who doesn't have admin tries to run the command

slate swan
paper sluice
slate swan
paper sluice
#

print(repr(error)) that will show the type

#

it is supposed to be MissingPermissions though, does it not get caught by it?

slate swan
#

I think I understand the problem

#

1 sec

slate swan
#

I understood my mistake. Basically I was getting an error from a command that was not supposed to exist. @paper sluice

#

I have 2 commands, one that sets the channel and one that sends the suggestion. I was putting for the errors of setting a channel in the errors of sending the suggestion. Since it was not the "send suggestion" command that was getting the error, it would never show the error message.

paper sluice
slate swan
#

ah well u are right

paper sluice
slate swan
#

yes.

#

and theres no errors just it doesnt respond

paper sluice
#

do you have an error handler?

slate swan
#

its suppose to be like this

#

no

paper sluice
#

put some prints inside on_member_join and see where it is breaking

slate swan
#

wym some prints

vale sierra
#
    if carabine[0] > 0:
TypeError: '>' not supported between instances of 'str' and 'int'
``` I have this error. Someone know how to fix it please ?
#
tools_ = [f"{i} x{j}" for i, j in itertools.zip_longest(tools_list, tools) if 0 < j < 1000000000000]
TypeError: '<' not supported between instances of 'int' and 'str'
``` same here
vale sierra
tough lance
pine marsh
#

anyone wanna help with a discord embed. Iโ€™m not trying to make embeds. Iโ€™m trying to read them and output select info from them to tweepyโ€ฆ #help-chili

swift acorn
#

I'm using on_raw_reaction_add(payload): event, and I want to remove the reaction that has been added, I can't find a way to remove the reaction that was added could anyone help?

slate swan
#

hello, I'm looking for someone who could modify my code because I didn't manage to get the result I wanted

#

This is what I would like

#

and this is the result I got

#

and this is the code : ```py
import discord
from discord.ext import commands
from http import client

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='.', intents=intents)
guild = 972222588828942337
channel = 993653876626563122
@bot.event
async def on_message(message):
res = f'content: {message.content}' + "\n" + f'user: {message.author}' + "\n"
if message.author.bot:
return
res = res + f'attachments:' + "\n"
await bot.get_guild(guild).get_channel(channel).send(res)

bot.run('token')

slate swan
hidden snow
#

hey is it against tos to dm people with a bot, im tryna do player registration for something and want them to be dmd by a bot to accept or deny

slate swan
hidden snow
#

dope ty

swift acorn
#

I'm trying to use user.roles, user is a user in my command and I've used user.roles in other commands but now it says that 'User' object has no attribute 'roles'

vale sierra
slate swan
vale sierra
swift acorn
slate swan
vale sierra
swift pumice
#

is the intents thing no a must do thing?

slate swan
swift pumice
#

cant you use ur bot without the intents

slate swan
#

yes

slate swan
#

you can

swift pumice
#

ok

#

just wanted to ask

slate swan
unkempt canyonBOT
#

@slate swan :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 1, in <module>
003 | TypeError: '>' not supported between instances of 'int' and 'str'
slate swan
#

an idea on your error

vale sierra
slate swan
#

well i cant really know types but try it

vale sierra
slate swan
#

๐Ÿ˜” why did I write that I wanna cry

vale sierra
#

?

slate swan
#

who stopped you

#

i did

#

for channel.history is there a limit to how many messages you can retrieve? anyone know

safe obsidian
slate swan
#

๐Ÿ™

safe obsidian
#

heh

vale sierra
#

@slate swan did you have any idea ?

slate swan
#

ah dang okay

#

thank you

vale sierra
#
@commands.command()
    async def inv(self, ctx):
        animal_list = [None, "๐ŸฆŠ Renard", "๐Ÿบ Loup", "๐Ÿฑ Chat", "๐Ÿฆ Raton-laveur", "๐Ÿฏ Tigre", "๐Ÿฆ Lion", "๐Ÿ† Lรฉopard", "๐ŸฆŒ Biche", "๐Ÿฆ“ Zรจbre", "๐Ÿฆ„ Licorne"]
        tools_list = [None, "๐Ÿ”ซ Carabine", "๐ŸŽฃ Canne ร  pรชche", "โ› Pioche"]

        db = sqlite3.connect("eco.sqlite")
        cursor = db.cursor()

        cursor.execute(f"SELECT * FROM animals WHERE user_id = {ctx.author.id}")
        animals = cursor.fetchone()

        cursor.execute(f"SELECT * FROM tools WHERE user_id = {ctx.author.id}")
        tools = cursor.fetchone()

        animals_ = [f"{i} x{j}" for i, j in itertools.zip_longest(animal_list, animals) if 0 < j < 1000000000000]
        tools_ = [f"{i} x{j}" for i, j in itertools.zip_longest(tools_list, tools) if 0 < j < 1000000000000]

        animals_ = "\n".join(animals_) if len(animals_) > 0 else "*No animals in Inventory*"
        tools_ = "\n".join(tools_) if len(tools_) > 0 else "*No tools in Inventory*"

        embed = discord.Embed(title="๐Ÿ’ผ Inventaire", description="", color=0xec0c0c, timestamp=ctx.message.created_at)
        embed.add_field(name="๐Ÿถ Animaux :", value=animals_)
        embed.add_field(name="๐Ÿ”ง Outils :", value=tools_)
        embed.set_thumbnail(url="https://cdn-icons-png.flaticon.com/512/5434/5434458.png")
        embed.set_footer(text=f"Rรฉpertoire de {ctx.author.name}", icon_url=ctx.author.avatar_url)

        await ctx.send(embed=embed)
```  Hello, with this part of code (Inventory relied to DB) i have this error :
hardy yoke
#

j is a string you need to convert it to an int

vale sierra
hardy yoke
#

it doesn't make sense to ask if a string is less than a int

vale sierra
hardy yoke
#

it needs to be an int yes

vale sierra
hardy yoke
#

int(j) would convert the number in j to an int

#

If j does not have a number, but rather a word (e.g "dog"), then the comparison doesn't make sense. Might need to explain what ur trying to acomplish

vale sierra
hardy yoke
#

๐Ÿ‘

vale sierra
#

have a good evening and slava ukraini brother

slate swan
#

I have a changeprefix command that goes into prefixes.json and changes the prefix to what was requested. I made a error so that if they dont pass in all the requirements it will just send the server's prefix. but instead of the servers prefix I get whatever's in the prefixes.json file

Code:

@changeprefix.error
async def changeprefix_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        with open('prefixes.json', 'r') as f:
            prefix = json.load(f)
        await ctx.send(f'My Prefix in this server is {prefix}')```
slate swan
slate swan
# slate swan how?

if you are using json, you should know how to work with it, select the guild id from the data

fleet sand
#

Does anyone ever write a discord bot that also send whatsapp message?

slate swan
slate swan
fleet sand
#

It's a discord bot that also send whatsapp message

#

Anyone ever wrote that?

#

Like the notification can be sent through whatsapp too

slate swan
#

wait

crimson compass
#

ฮ„?

slate swan
# slate swan no?

i get this massive error
[2022-07-07 13:36:17] [ERROR ] discord.client: Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1330, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 987, in invoke
await self.prepare(ctx)
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 904, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 811, in _parse_arguments
transformed = await self.transform(ctx, param, attachments)
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 663, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: prefix is a required argument that is missing.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 182, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Clicks\Desktop\Timmy (smile)\bot.py", line 358, in changeprefix_error
await ctx.send(f'My Prefix in this server is', prefix[ctx.guild.id])
IndexError: list index out of range

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 456, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1375, in on_message
await self.process_commands(message)
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1372, in process_commands
await self.invoke(ctx) # type: ignore
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1334, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 607, in dispatch_error
await injected(ctx, error) # type: ignore
File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 188, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: IndexError: list index out of range

#

which doesnt make any sense

slate swan
crimson compass
#

ฮท ฮดฮนฮบฮนฮฑ ฯƒฮฟฯ… ฮผฮต ฮณฮฟฯ…ฯƒฯ„ฮฑฯฮตฮน ฮปฮตฮตฮน ฮฟฯ„ฮน ฮตฮนฮผฮฑฮน ฮบฮนฮฟฯ…ฯ„

slate swan
#

hellish

slate swan
slate swan
slate swan
# slate swan <:sped_pepe:934469745900683404>
Traceback (most recent call last):
  File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 456, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1375, in on_message
    await self.process_commands(message)
  File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1372, in process_commands
    await self.invoke(ctx)  # type: ignore
  File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\bot.py", line 1334, in invoke
    await ctx.command.dispatch_error(ctx, exc)
  File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 607, in dispatch_error
    await injected(ctx, error)  # type: ignore
  File "C:\Users\Clicks\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ext\commands\core.py", line 188, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 990034346490597427```
#

Are you using .get?

slate swan
# slate swan Are you using .get?
@changeprefix.error
async def changeprefix_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        with open('prefixes.json', 'r') as f:
            prefix = json.load(f)
            prefix.get(ctx.guild.id)
        await ctx.send(f'My Prefix in this server is', prefix[ctx.guild.id])```
#

oh god

slate swan
#

string it

#

And also make sure that the guild id is in the dict

#

Thatโ€™s always useful

slate swan
#

im joking

slate swan
#

Iโ€™m playing rainbow six Seife

#

Seige

#

nobody asked, go and play

swift pumice
#

Hi, is making a level system hard?

slate swan
#

Depends

spring flax
swift pumice
#

i dont know anything about databases

slate swan
slate swan
#

doubt

spring flax
#

How do you do it then?

swift pumice
# slate swan N O

can you tell me what i need to do? (dont send me a code) i just want to know what i need to do

slate swan
#

I stringed it but I didnt add all the reqs

swift pumice
#

and ill try myself

slate swan
#

this is what I did:

#
prefix.get[str(ctx.guild.id)]```
slate swan
slate swan
#

Plus itโ€™s free and made by Google

swift pumice
#

okay

slate swan
#

SQL ftw ๐Ÿ˜”

swift pumice
#

thank you guys

spring flax
#

Sqlite is also a good option imo

slate swan
#

postrgreSQL is suggested

#

but sqlite works good enough

spring flax
#

If its small, postgresql may be a bit...unnecessary? I think

swift pumice
spring flax
#

Database

slate swan
#

Stores data

spring flax
#

Is that what you meant?

slate swan
#

A database is just a storage method and is used for persistent data operations.

swift pumice
#

okay

#

thanks

slate swan
#

Heโ€™s saying something about discord bots

safe obsidian
#

absolutely not ๐Ÿ˜‚

slate swan
#

Itโ€™s a good guess

#

Considering this is the discord bots channel

#

What is the discord error if a required argument is missing

#

Is it just MissingRequiredArgument ?

flat solstice
#

Hi I'm just wondering if it's possible to do this```py
view = View()
if persistant is not True:
view.add_item(AlphaDropdown())

elif persistant is True:
view.timeout=None
view.add_item(PersistentDropdown())instead of thispy
if persistant is not True:
view = View()
view.add_item(AlphaDropdown())

elif persistant is True:
    view = View(timeout=None)
    view.add_item(PersistentDropdown())``` when setting the timeout of a dropdown (d.py 2.0)
slate swan
slate swan
vale sierra
#
if int(carabine[0]) > 0:
``` hello, what is the correct syntax to convert str in int in this code ? i have this error :
slate swan
#

show the list carbine

#
@client.command(aliases=['magic8ball'])
@commands.cooldown(1,3, commands.BucketType.user)
async def _8ball(ctx, *, question):
    responses = ["It is certain.",
                "It is decidedly so.",
                "Without a doubt.",
                "Yes - definitely.",
                "You may rely on it.",
                "As I see it, yes.",
                "Most likely.",
                "Outlook good.",
                "Yes.",
                "I am 1000% sure of it",
                "Signs point to yes.",
                "Reply hazy, try again.",
                "Ask again later.",
                "Better not tell you now.",
                "Cannot predict now.",
                "Concentrate and ask again.",
                "Don't count on it.",
                "My reply is no.",
                "My sources say no.",
                "Outlook not so good.",
                "Very doubtful."]
    embed=discord.Embed(color=0x00ff11)
    embed.add_field(name=f'Question: {question}')
    embed.add_field(name=f'Answer: {random.choice(responses)}')
    await ctx.send(embed=embed)```
#

nothing is being sent

#

whys embed now defined?

wicked atlas
slate swan
#

ah ok

slate swan
slate swan
vale sierra
slate swan
#

Show the actual [โ€œ1โ€,โ€2โ€,โ€3โ€]

vale sierra
#
if int(carabine[0]) > 0:
```  hello, what is the correct syntax to convert str in int in this code ? i have this error :
slate swan
#

print(carbine[0]) for me

vale sierra
#
if carabine[0] > 0:
``` error : so i want to convert it into a int
slate swan
#

Ok bro

#

Print(carbine[0])

#

And I can help you

vale sierra
#

go ahead

#

what i should change ?

slate swan
wicked atlas
#

Make sure the values in your list are values that can actually be converted to an integer, then use the int() function to convert it to one

vale sierra
wicked atlas
#

Show the values in carabine

slate swan
wicked atlas
#

And be more specific about "dont work". In what way did it not work?

slate swan
#

Well he gave the error

wicked atlas
slate swan
#

Print(carbine[0])

#

How many times

wicked atlas
# vale sierra

int(carbine[0]) is fine. The error you send in your first screenshot probably happens on this line

cursor.execute(f"UPDATE tools SET carabine = ? WHERE user_id = ?", (carabine[0] - 1, ctx.author.id))
#

You're trying to subtract 1 from carabine[0], which is a string

slate swan
#

why are you storing the numbers in carabine as strings

#

True

wicked atlas
#

very good question

slate swan
#

But Print(carbine[0]) for goodness sake

#

Itโ€™s not like itโ€™s gonna end the world

#

Iโ€™m positive itโ€™s either gonna return โ€œ[โ€œ or a string that isnโ€™t an int

wicked atlas
#

They have yet to show a ValueError, so I'd say it won't

slate swan
#

Bruh they dipped

wicked atlas
#

lol

slate swan
#

I swear some people who ask questions here are bots themselves

slate swan
#

I need help

#
import asyncio

import discord
import random
from discord.ext import commands

TOKEN = 'no'
activity = discord.Activity(name="VALORANT", type=discord.ActivityType.playing)
client = discord.Client(activity=activity)
prefix = commands.Bot(command_prefix='.')

@client.event
async def on_ready():
    print(f"We have logged in as {client.user}")

@client.event
async def on_member_join(member):
    print(f'{member} has joined the server.')

@client.event
async def on_member_remove(member):
    print(f'{member} has left the server.')

client.run(TOKEN)
#

The code wont work for the on_member_join and on_member_leave

#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

what

#

intents?

#

Do I need to activate them

#

the priveledged gateway

#

yes, read the whole embed!

#

for those commands to work

slate swan
#

yeah no intents instance

#

yea but

#

pls read the whole embed :))

#

I diddd

#

Let me finish

#

What I am trying to say is like since I used @client.event and I changed it to bot I would need to do @bot.event correct?

#

Sorry I didnt mean to be rude

#

that is correct only have the bot instance and have intents on

#

and ofc run the bot with its instance so remove client

slate swan
#

yup!

#

tysm

slow fog
#

SUS

slate swan
#

how?

slate swan
#

๐Ÿคจ

#

new problem @slate swan

#

whatsup?

#
import discord
import random
from discord.ext import commands
from discord import Intents

intents = Intents.default()
intents.members = True
TOKEN = 'none'
activity = discord.Activity(name="VALORANT", type=discord.ActivityType.playing)
client = discord.Client(activity=activity)
bot = commands.Bot(command_prefix='.', intents=intents)

@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")

@bot.event
async def on_member_join(member):
    print(f'{member} has joined the server.')

@bot.event
async def on_member_remove(member):
    print(f'{member} has left the server.')

bot.run(TOKEN)
#

Basically the status wont show anymore

#

the activity and client lines

#

those create the status but it doenst work anymore

#

put it in your bot

#

not client

#

add a comma?

#

remove this line

client = discord.Client(activity=activity)

and just pass activity to your bot instance

#

Wait

#

So like this:

bot = commands.Bot(command_prefix = '.', intents=intents, discord.Client(activity=activity)
#

No

#

no no, remove discord.Client

#

Oh

#

and the opening parenthesis (

#

so just

#

activity = activity

#

why do we use bot instead of client tho

#

in your bot constructor yes

#

dont discord.Client and commands.Bot do the smae thing?

slate swan
#

Oh'

slate swan
#

Ok

#

!d discord.ext.commands.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.
slate swan
#

oh

#

so it has more features nice

#

yup

#

weird lol

#

tysm tho

#

๐Ÿ‘

#

now ima check if this works

#

Wait so in the bot instance we can put anything in the arguments?

#

is there an api for this subclasss or any resources

#

you can use random kwargs because of **optionsyes

#

Ight

slate swan
#

just press the blue title in the embed and you will see all of its attributes and methods

#

ok

#

ty

#

โค๏ธ

#

What do functin decorators even do?

#

@slate swan for example @bot.event or @bot.command

#

Do they have any purpose or is it like commenting

slate swan
#

!function_decorator

#

!d help

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
slate swan
#

whats a dpy lib abstraction

#

lol

#

sorrrry im a very curious person

#

well discord.py has its own code structure/code base, and lib abstractions is basically a feature the library offers, e.g the command structure

slate swan
#

you can use pykawaii

#

!pypi pykawaii

unkempt canyonBOT
slate swan
#

thanks

flat solstice
#

how can I get the id of a interaction msg? I tried static = await interaction.response.send_message() then static.id but got told NonType object has no attr 'id'

slate swan
# slate swan thanks

its docs is broken, i should fix that, its pretty easy and if you have questions just tell me ๐Ÿ˜…

#

yeah i do idk really know how i would set this up? i have it installed pip and it imported though

slate swan
slate swan
#

yea i am just a lil confused

slate swan
#

yea i downloaded the winrar and im checking it atm

#

alr

unkempt canyonBOT
flat solstice
slate swan
#

the method doesnt return anything

#

maybe you might know this @slate swan i get this error keyerror 'url'

slate swan
#

probably a 400, so print the response

#

wym probably a 400?

#

the HTTP code

#

hello I hjad a questionm

#

@bot.command(aliases =['8ball', 'test'])
async def _8ball(ctx, *, question):
    responses = ['It is certain.',
                 'It is decidedly so.',
                 'Without a doubt',
                 'Yes definitely.',
                 'You may rely on it.',
                 'Reply hazy, try again',
                 'Ask again later.',
                 'My sources say no.',
                 'Outlook not so good.',
                 'Very doubtful.']
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
#

I was wondering what does the asterick do?

#

I was following a YouTube tutorial

slate swan
#

Huh

#

!args-kwargs

unkempt canyonBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
โ€ข Decorators (see !tags decorators)
โ€ข Inheritance (overriding methods)
โ€ข Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
โ€ข Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

slate swan
#

oh right you wanted to know about decorators too

#

ye

#

!tags decorators

unkempt canyonBOT
#

Decorators

A decorator is a function that modifies another function.

Consider the following example of a timer decorator:

>>> import time
>>> def timer(f):
...     def inner(*args, **kwargs):
...         start = time.time()
...         result = f(*args, **kwargs)
...         print('Time elapsed:', time.time() - start)
...         return result
...     return inner
...
>>> @timer
... def slow(delay=1):
...     time.sleep(delay)
...     return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!

More information:
โ€ข Corey Schafer's video on decorators
โ€ข Real python article

slate swan
#

i think neko.py is fucked? idk im talking to my friend who help me set it up originally and thats what he sia

slate swan
#

posistional vs keyword arguments means what?

#

!positional

unkempt canyonBOT
#

Positional vs. Keyword arguments

Functions can take two different kinds of arguments. A positional argument is just the object itself. A keyword argument is a name assigned to an object.

Example

>>> print('Hello', 'world!', sep=', ')
Hello, world!

The first two strings 'Hello' and world!' are positional arguments.
The sep=', ' is a keyword argument.

Note
A keyword argument can be passed positionally in some cases.

def sum(a, b=1):
    return a + b

sum(1, b=5)
sum(1, 5) # same as above

Somtimes this is forced, in the case of the pow() function.

The reverse is also true:

>>> def foo(a, b):
...     print(a, b)
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1

More info
โ€ข Keyword only arguments
โ€ข Positional only arguments
โ€ข !tags param-arg (Parameters vs. Arguments)

flat solstice
left idol
#

if i have an async function that does some stuff and returns some variables, how can i get these variables inside of my command function?

slate swan
slate swan
#

which mine has objs

#

where would i find tht?

#

on the github

#

yeah

#

check its examples in the read me or src