#discord-bots
1 messages ยท Page 1139 of 1
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
!d discord.ui.View you use discord.ui.Button to make buttons, then you add the buttons to view and send it with the embed
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.
like this:
...
view = discord.ui.View()
view.add_item(discord.ui.Button(...))
ctx.send(embed=embed, view=view)
?
why would u create a database for prefixes
just create one db and create a prefix table in that
How to fix this?
f
.
rip
Ig i did something silly wrong
even the sql operations are wrong, I think i'll create an example for custom prefixes
Whats wrong in it?
almost the whole thing
Tf
ur approach of using db is wrong
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
I made one db bro
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
Oh means i should do
setup_hook() where i need to connect?
do u open and close the door of ur room everytime i enter or exit ๐ same principle
yes since setup hook is called once when the bot starts
Ok
,
u can even make a .py file for all SQL db and tables and run that function in the setup hook
.
๐ณ
I am confused how to do
wait ashley is writing a tutorial

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
Is it correct now.
I literally made a custom prefix shit in 5 minutes and it works
You pro
no
My brain is 10%
same as Einstein's ๐
Bruh
couple of thing, you didnt define bot.cursor, connect is not a variable in the scope of get_prefix, you are closing connection in connection fn so then you can't usebot.connect
and you don't commit when you select data, you only commit when you edi the table/db
i use that 1% in all the wrong places :/
โ๏ธ
just don't it :))
my brain usage chart
.5% python
.4.9% other stuff
.01% study
?
What you mean other stuff?
๐ฉ
i was watching like a 4 part documentary on basketball players being high and taking pills to lower down b4 games
in the 1980s*
@shrewd apex do you have yt ch?
no
sheesh

i will just be watching random stuff from yt or read some novels
finally got this working ( again )
Me watch python tut but learn nothing
nice none of my message commands work...
reading novels is nice, i stare at my monitor for like 14-18hrs a day
pog
helpp ๐ญ
20-23 for me
๐
Me watch 2hrs
you are a different breed? you wear glasses?
๐
You mean animal?
ofc I dont wanna go blind
I not got glasses yet
i need glasses, but i wont get em ๐
Wearnung glasses is like a dare
the only time I remember getting glasses were colourblind glasses and blue light filter
๐ท
๐
I bored
sleep
I already slept a lot
cry
Hmm for what reason
aint no tears left to cry
Ig i should cry for python
why have a reason when it doesnt cost you anything
๐ just dont apply that statement to wrong stuff pliz
light theme!! that is why they are crying
๐ง
๐ฅ
Anyone here have any tutorial on sqlite?
I mean for discord bots
i know one for pgsql
idk for aiosqlite
but the pgsql one is kinda well not too pro
its literally sqlite, there is nothing more to it
But my this is not working
any errors?
u might want to look at the code first
idk i cant see any issues at first glance
get glasses
lmao
no
that code doesnt even make sense
^^
just like our lives....
idk dude ยฏ_(ใ)_/ยฏ
Ye you can expect this from me
sending the error will help though.
Ok I'll send
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")
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 
its new in dpy 2.0 and thats not how u use setup hook ;-;
you forgot the comma, it should be (id,) not (id),
oh, i have lost in touch with the new features 
๐
Now i need to make the set_prefix
How we can use bot mention as a prefix?
there was a mentions_or function iirc
when_mentioned_or
lol setup_hook looks like a good way to create deadlocks ๐คฃ
!d discord.ext.commands.when_mentioned_or
discord.ext.commands.when_mentioned_or(*prefixes)```
A callable that implements when mentioned or other prefixes provided.
These are meant to be passed into the [`Bot.command_prefix`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.command_prefix "discord.ext.commands.Bot.command_prefix") attribute.
Example
```py
bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'))
```...
...
?
commands.when_mentioned_or(get_prefix)
Thanks
I am getting one error because of it
return the prefix from get_prefix function
I returning
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()
tell me if u are returning how is the commit and close working
print the prefix and see
Prefix table empty yet
Someone told me
bot will be passed if you use it or not
How can we update the cell in sqlite?
Means i want to update the prefix where guild Id is message guild id
UPDATE table
SET
column=?
WHERE guild_id=?
UPDATE prefixtab SET prefix='any' WHERE guild_id=?, (id,))
Is it correct?
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
await cursor.execute('UPDATE prefixtab SET prefix=? WHERE guild_id=?',(newpre,id))
I made for updating prefix
Oof it's not returning
How can I fix it?
Pls help
๐ฅบ
print prefix and see whats wrong
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
It's printing the default prefix not the fetch one
I got this error
@paper sluice i got this error
https://media.discordapp.net/attachments/343944376055103488/994597000915976253/Screenshot_2022-07-07-19-03-04-45.jpg
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
But when i run the code and when there is an event, it doesnt send the message however it logs it on heroku(host)
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
oh well that sounds complicated a bit for me i havent dealt with any kind of web scrapping before
i cant help
thats fine, the scraping works ok, but it doesnt send the message on discord
it logs it on the console
@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 !
my friend is using it, it works for him
any YouTube tutorials recommended?
any youtube tutorials recommended for me to start setting up a discordbot.py
? no the error is what i send
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
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.
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.
theyre using the same thing
how can i fix this ?
okay... also any idea on why it logs the stuff in the console
@slate swan :white_check_mark: Your eval job has completed with return code 0.
('a', 'd') ('b', 'e') ('c', 'f') (None, 'g')
the same length ?
They just said its supposed to work
well, ur passing a NoneType as prefix
fixed the problem, thats wasnt this but thanks
Means?
Is it possible to fix it?
means you basically doing command_prefix=None in the commands.Bot's constructor
That point just use a Client
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?
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
I getting this error now ๐ข
sparky has been typing for the past 30 mins
show code
Sqlite annoying
it isnt...
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()
No I didn't I was just reading I didn't type a single letter also I'm back home my net is fine
remove the commit you don't need it, you only need it when you are modifying the table
i saw u typing multiple times lol
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
host it in a vps, if you want to know about vps check out #965291480992321536
what is reasons.py and stats.py?
cogs? files with functions you use in ur code?
the reasons.py contains the class for a Select Menu and stats.py gives the user stats from a mysql db
I just came across
that and dk how to use it with current Functionality.
hi guys, can someone help me wit my bot, i want to save the authors message, but i cant
save it where?
so, about file structures, you want to group similar type of files in one dir
like if you have cogs, you put them in one dir, if you have files which contain random thing you need, you put them in one directory
a good example is @unkempt canyon you can check out the source for the bot using !src
oh, then what about .env file?
im not the best in eng save in variable translater gives
cogs are means to spread commands into multiple files, so that you don't have one massive file containing all commands
oh, can you share your code?
alright, I'll try that Ty!!
just keep it where its easily accessible
test = await client.wait_for('message')
await ctx.send(f"You wrote: {test}")
alrightt, thanks again
@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
insted of test, try putting test.content
ty
@winter gull if im working with TEST, i want to make it smaller for exampler, im working with my thue message, right?
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
sad /tts noises
๐
use .lower()
im sorry, but where?
@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
bro do embed=no_meme
Still not working ๐ญ
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}")
Just remove the description
Still not working
that works?
Otherwise use normal string
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
Yeah
cool
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
test is an instance of Message, you can access its content with content attribute
Hi
Still not working
it gives me a bunch of errors
It says Unsolved Reference
Whenever the message comes up
Don't make commands in on_message
Don't use client
use bot
huh
Find a tutorial that teaches about using @bot.command decorator
so what do I change? I was just following a youtube tutorial
Bad tutorial bro
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....
What if bot = discord.Client()
That one
like this? (dont working)
For only listening to events it's okay
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
If this tutorial uses on_message for commands then its author has too few knowledge
Okay
I have one in my repo but it's unfinished
@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
test[0].content, the message is not subscriptable unlike content
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.
!d discord.ext.commands.Bot.command
@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").
Hello, how can I fix this error?
And I think there's a good example but somewhere else
Install newer version of lib
@vale wing
@slate swan
lol
wait_for("message") returns the message object
so how can i work with test as a string?
lib of python ?
Discord
so how can i work with test as a string?
so how can i work with test as a string?
I already told you
Ask someone else if my explanation wasn't clear, I am not a spoonfeeder

sorry my eng isnt that good i cant find your answer what whould i whrite to work with test as a string
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
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
Wdym?
im too bad
but when i write hi bot he doesnt answer
how do I install version 2.0?
pip install -U git+https://github.com/Rapptz/discord.py
Well you must be checking if the whole message is hi.
You need to check if hi is in the message
if "word" in your_string
uhh put the test.content in a string and do this <string>.lower() where <string> = your string name
i got test from discord.Message from wait_for('message')
so, what should i whrite to work with test as a string, to do test[0] for example? I cant catch sorrry
You can't work with Message as a string cause it's not one
Didn't you just said you don't spoonfeed ๐
๐
You can only work with its content which you most likely need
Well what else could you tell to him
so on the front of my string i have to put word not message right
Wut
mate i am confused as fuck
!e print("hi" in "hi dude")
@vale wing :white_check_mark: Your eval job has completed with return code 0.
True
You basically get a bool from that
like this?
test = await client.wait_for('message')
test=test.lower()
sss=test[0]
await ctx.send(f"You wrote: {sss}")
test is not a str
how to make it string?
MError
i myself know c++, but c++ discord lib is bad, so i try work with python
Ok I encourage learning but learning python from a discord bot is not a good idea with zero of python knowledge
You know c++ at like what level? Loops, functions, classes?
i can make a chess game, worked with maps, massives, vectors etc \
Cool
That's truly cool but you should learn about OOP for python
Object oriented programming
Eh I didn't want to do this till the last moment
test.content
Ok now I am a spoonfeeder ๐
Haha
my eng is 0, my python is 0, and your jokes are ununderstandable
๐
gor me
He's joking about me but ok
i mean this you whrite haha so @vale wing joked
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)
No way my AI bot got 3 stars on repo, that's the max I have ever reached lmao
Probably your encoder is blocking
Although I can't tell exactly
But seems like it is
Run your encoding process in executor
I don't remember its name
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object is not callable new mistake guys
Basically asyncio.get_event_loop().run_in_executor(None, your_func)
progress incoming
there is always a mistake
Don't call
Event
How do I call it to make it work?
You don't
You decorate a func with it, the decorator doesn't require arguments actually ๐ค
im trying this:
test = await client.wait_for('message')
sss=test.content[0]
await ctx.send(f"You wrote: {sss}")
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 ?
@sick panther, please enable your DMs to receive the bookmark.
Lol
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')`
check if str is empty, then index it. Or just put it in a try-except
do message.guild instead of client.guild
tysm
it is not empty because i enter it
test = await client.wait_for('message')
sss=test.content[0]
await ctx.send(f"You wrote: {sss}")
now it says this but i think it might be a similar issue?
AttributeError: 'int' object has no attribute 'send'
.id returns int, so you can't send it using that
remove the .id
oh ok
may i ask, why do you want the first element of the message?
i want to work with test as a string, for my all work i need to take the message and replace the date from it to 2 lists and work with them
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)โ```
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.
how is that related to the first index of the string?
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?
if i cant work with it as a string how can i make my work?
wym by thatr
actually, fetching users in on ready is a bad idea, cuz thats just how discord api is built
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,
!d discord.ext.tasks.loop
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").
i am creating a task loop when on ready
and so are you
There is a time Param
no, listen
Time Param makes the loop run at specific intervals
@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
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
๐ญ๐ญ๐ญ๐ญ
I mean it rakes datetime.time as parm
first of all, you are spamming the api, try put a sleep there, and there are commands.tasks for this
where
alright
thanks
i still don't understand why you need the first index specifically
whats the none for?
Default executor
ah
You can specify some other if you would like to
@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 
Default one works fine imo
Subclass help command for god's sake
Also help is a builtin
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
you can, python doesn't stop you
Weird how people face issues with overriding it exclusively in dpy
Anyway overriding builtins is a bad idea generally
Except of course
id
can i pass details from a var in it to code below the executor?
@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'
type hint amount with int
I already tried that and it gave an error
no
what error?
only serves to organize
**Command raised an exception: TypeError: '>' not supported between instances of 'str' and 'int' **
u didnt type hint as i said
that is not a type hint
thanls
error bro
ok thanks
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
you can reference to this and make something like these helper functions -> https://github.com/Ash-02014/Yuuki/blob/main/Yuuki/utils/utils.py#L23-L42
yeah ive reference everywhere i just caint seem to figure it out
so whats the alternate thing
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.
no, they also give you commands.task(time=) kw param, which was what i needed.
!d discord.ext.commands.Bot.wait_until_ready
you will need to wrap it in something
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.
What does that mean
that's a
def after_play():
loop = asyncio.get_event_loop()
loop.run_until_complete(after_audio_finished)
voiceClient.play(source, after=after_play)
music bot
this is what i mean
do i use asyncio.time(5)
I did that
But it says I have to await it
await what?
If it's after=after_play it isn't being awaited the function
It's an async function
asyncio.sleep()
You did def not async def like I did
@slate swan
is voiceClient.play a coroutine?
i know what i did
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.
I want functions but i cant send stuff or do functions on discord without it being async
that gives me an error and says unsolved reference
@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
you need to await asyncio.sleep
Ok
but where do you have asyncio sleep here, you dont have it
I got rid of it
interesting
It was above the line that declared user
do f strings,
oh
Can I send it to u on dms
yes
ok they are closed
friend request sent
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
?
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
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.
if i have a previously defined function, can i use it inside of my command function?
maybe the person has permissions?
yes why not?
it doesn't. The error message (discord.py's default message) appears on the console
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
show code
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
do you have member_content intent enabled?
i dont think no
it doesnt send a message because you are printing to the console not sending anything
then do intents.message_content = True before passing it in commands.Bot
alright will do
that is not the problem
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
commands.Bot?
well, maybe MissingPermissions is never raised
you use discord.Client?
and how do I solve that?
@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
ya now do
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(..., intents=intents)
like this?
do you have it set so that people will certain perms can interact with the cmd?
@commands.has_permissions(administrator = True)
async def channel(self, ctx, channel: discord.TextChannel):```
no, in ur case just do client = commands.Bot(command_prefix='>>', case_insensitive=True, intents=intents)
does the command work? is suugestionCommand a group or something?
you need to define intents, as i did b4
someone to help me please ?
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
oh, r u on discord.py 1.7.3?
it prints the standard message that the person does not have the administrator permission.
print(repr(error)) that will show the type
it is supposed to be MissingPermissions though, does it not get caught by it?
i shouldnt be? no
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.
no, type pip show discord.py in ur terminal and you will see the version there
ah well u are right
so the bot is not responding when a member joins the guild?
do you have an error handler?
put some prints inside on_member_join and see where it is breaking
wym some prints
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
carabine[0] is not an int
here the full error :
Bro carabine[0] is not int. It returns a string
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
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?
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')
you send the attachment using the file kwarg and pass in a discord.File object
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
file = discord.File("uwu.jpg")
await obj.send("uwuwuwuwuwuuw", file=file)
no it's not
dope ty
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'
thats the full error
a discord.User class is a representation of a user discord account which has no roles since its an account, discord.Member class is a class is a representation of a user inside a guild which guilds do have roles
ik that's just the error
O yeah figured it out I had to use guild.get_member, thanks a lot tho
member = interaction.user
if not isinstance(user, discord.Member):
member = get_member(...) or await fetch_member(...)
is the intents thing no a must do thing?
what?
cant you use ur bot without the intents
yes
if not interaction.guild:
member = get_member(...) or await fetch_member(...)
less chars
you can
okay boomer
๐
!e
if 1 > "ok":
print("lmao")
@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'
an idea on your error
animals_ = [f"{i} x{j}" for i, j in itertools.zip_longest(animal_list, animals) if j > 0 and j < 1000000000000]
```is it better ?
well i cant really know types but try it
same error
int("ok")
๐ why did I write that I wanna cry
?
youre making me wanna learn java
who stopped you
i did
for channel.history is there a limit to how many messages you can retrieve? anyone know
pls dont do this ๐
๐
heh
@slate swan did you have any idea ?
2 weeks
ah dang okay
thank you
@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 :
is 9 < a
j is a string you need to convert it to an int
what ?
it doesn't make sense to ask if a string is less than a int
yes so i need to convert it ?
it needs to be an int yes
how can i do it ? do you have a code example pls ?
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
thanks it work
๐
have a good evening and slava ukraini brother
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}')```
select a key smh
how?
if you are using json, you should know how to work with it, select the guild id from the data
how
Does anyone ever write a discord bot that also send whatsapp message?
dude
prefix[guild_id] and make sure that the key is an str
its a discord bot not whatsapp
It's a discord bot that also send whatsapp message
Anyone ever wrote that?
Like the notification can be sent through whatsapp too
like this?
@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 = [str(ctx.guild.id)]
await ctx.send(f'My Prefix in this server is', prefix[guild_id])```
wait
no?
lmao. ik what i did wrong
ฮ?
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
prefix.get(guild_id) ๐ด๐ด๐ด
ฮท ฮดฮนฮบฮนฮฑ ฯฮฟฯ ฮผฮต ฮณฮฟฯ ฯฯฮฑฯฮตฮน ฮปฮตฮตฮน ฮฟฯฮน ฮตฮนฮผฮฑฮน ฮบฮนฮฟฯ ฯ

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

very helpful
ctx.guild.id returns an int
string it
And also make sure that the guild id is in the dict
Thatโs always useful
with open('prefixes.json', 'r') as f:
prefix = json.load(f)
await ctx.send(f'My Prefix in this server is {prefix.get(str(ctx.guild.id))}')
Iโm playing rainbow six Seife
Seige
nobody asked, go and play

Hi, is making a level system hard?
Depends
Are you?
i dont know anything about databases
N O
How do you do it then?
can you tell me what i need to do? (dont send me a code) i just want to know what i need to do
I stringed it but I didnt add all the reqs
and ill try myself
use a db
with an on_message event/listener where you update the stats
Use a fire base database, itโs easy to set up and learn
Plus itโs free and made by Google
okay
SQL ftw ๐
thank you guys
Sqlite is also a good option imo
If its small, postgresql may be a bit...unnecessary? I think
what is a db when i could ask?
Database
Stores data
Is that what you meant?
A database is just a storage method and is used for persistent data operations.
wth
Heโs saying something about discord bots
absolutely not ๐
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 ?
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)
Yep
Try it and see if it works as expected
if int(carabine[0]) > 0:
``` hello, what is the correct syntax to convert str in int in this code ? i have this error :
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?
because you named it em, not embed
This does not show the carbine var
This still doesnโt show it
why do you mean by carabine var
Show the actual [โ1โ,โ2โ,โ3โ]
i just want to convert a str to a int if you can't help me that's not a problem
if int(carabine[0]) > 0:
``` hello, what is the correct syntax to convert str in int in this code ? i have this error :
Show the string you are trying to convert
print(carbine[0]) for me
if carabine[0] > 0:
``` error : so i want to convert it into a int

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
do you have a code example ?, i alr try this but its dont work : python if int(carabine[0]) > 0:
Show the values in carabine
Print(carbine[0]) and show us it
And be more specific about "dont work". In what way did it not work?
Well he gave the error
This error looks like it's happening on an entirely different line than the one you're showing
^
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
There isnโt any > operand
why are you storing the numbers in carabine as strings
True
very good question
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
They have yet to show a ValueError, so I'd say it won't
lol
I swear some people who ask questions here are bots themselves
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
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.
what
intents?
Do I need to activate them
the priveledged gateway
yes, read the whole embed!
for those commands to work
Wait look at my code though
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
at the end Ima change client.run(TOKEN)
to bot.run(TOKEN)
yup!
tysm
SUS
how?
sussy baka'
๐คจ

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?
because the bot class has more features
Oh'
its a subclass of Client
Ok
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
Represents a Discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
Unlike [`discord.Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client"), this class does not require manually setting a [`CommandTree`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree "discord.app_commands.CommandTree") and is automatically set upon instantiating the class.
async with x Asynchronously initialises the bot and automatically cleans up.
New in version 2.0.
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
no only documentation like the one given above
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
they can change a functions behavior
!function_decorator
!d help
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.
theyre just dpy lib abstractions for registering commands and events lol
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
hey thats fine so am i, thats how we learn after all!
im trying to make a nsfw command but https://github.com/Nekos-life/nekos.py doesnt seem to work anyone know?
you can use pykawaii
!pypi pykawaii
thanks
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'
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

check the read me
sorry i would need to take time and figure out the issue which is probably related to dirs but you can check its src code https://github.com/Okimii/pykawaii/tree/main/pykawaii/models
yea i downloaded the winrar and im checking it atm
alr
!d discord.Interaction.message
The message that sent this interaction.
so not just py static = await interaction.response.send_message(embed=embed, view=view, ephemeral=ephemeral) static.message.id someone on the dpy server said I should be using original_message https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.original_message
no no
the method doesnt return anything
maybe you might know this @slate swan i get this error keyerror 'url'
you probably got an invalid response
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
it makes all arguments after key word only
Huh
!args-kwargs
*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
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
i think neko.py is fucked? idk im talking to my friend who help me set it up originally and thats what he sia
have you checked the response?
posistional vs keyword arguments means what?
!positional
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)
Okay so I just added a self.add_view to my setup hook alongside a message_id of the msg with components that I want to stay persistent between restarts, restarted my bot and it's not listening to the interactions. I'm setting up my view here https://github.com/SnowyJaguar1034/ModMail-FAQ/blob/master/classes/faq.py#L33-L42 and this is how I'm grabbing the id of the interaction message that it listens to https://github.com/SnowyJaguar1034/ModMail-FAQ/blob/master/main.py#L103-L109
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?
yeah i just dont think neko works im trying yours again would something like this work