#discord-bots
1 messages · Page 1075 of 1
ok lets move on
yes pls
.topic
o๑p
making my bot self destruct
i am proud of a chat cmd
ping 😔
chat cmd?
oh mine does that +kill
elaborate so we can copy
Bot.latency 👁️ 👁️
lmao
Seems correct to me
ehhyes
mine shuts my whole pc down so it zombifies the ws connection😳
(ctx.guild.id, ctx.channel.id, 'xyz',)```
dayum thats further than mine
you incapacitate the machine
I already closed it but I didn’t add the , at the end yet so I’ll add it
what can i say im a talented human bean
just make it delete the source files and then shut down
seems fun to do
no ill make a new one that over loads my psu and makes my pc explode
you need to pass in a tuple as the second argument !!
🏚️
you have attained to point to shitposting now
like (ctx.guild.id, ctx.channel.id, "blah",) :3
i made my bot interact with console it was launched from
🥱….. ok
until ur mom is using the pc
😳
accepting console commands, to be precise
and it explodes
oh...um..yeah maybe
just use os.system
!d os.system
os.system(command)```
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function `system()`, and has the same limitations. Changes to [`sys.stdin`](https://docs.python.org/3/library/sys.html#sys.stdin "sys.stdin"), etc. are not reflected in the environment of the executed command. If *command* generates any output, it will be sent to the interpreter standard output stream. The C standard does not specify the meaning of the return value of the C function, so the return value of the Python function is system-dependent.
On Unix, the return value is the exit status of the process encoded in the format specified for [`wait()`](https://docs.python.org/3/library/os.html#os.wait "os.wait").
the opposite 🙂 getting user input from console
@slate swan we need your views, how was it?
be sure to vigorously sanitize any user input
it was small happy potato acchievement
it was beginnerish
it was ok
blocks the bots heart😔
I'll go to sleep, im reading weird things now instead of whats written

import aioconsole
inp = await ainput(">")
dont forget to turn of your phone or phone go || BOOM 💥 ||
await cannot be used outside of an async function
ah, top-level await lmao
Anyone able to show me an example of how to store user data?
For example, they type /token and it puts the value in a .db or .json?
Or just point me to the right video/article/thing
trust
reminds me I dont even have a screen proc yet, thanks okimii
ey wait
it was pseudo-code 😐
too bad my python interpreter(my brain) says its invalid😌
protip: if you pipe your code into python -m asyncio, you could do top-level await
installs patch into okimii's interpreter
never actually tried it, YMMV
monkey patching!
monkey patching a monkey 💀
on a typewriter
hellish
@slate swan my current errors are adding tuples so I’ll do that quickly
just do os.remove("C:\Windows\System32") for that top level async 😳
You need to know how to use sqlite3 for the same
i use linux 😦
asynchronous kill....
no top level async for you
fool me twice... can't get fooled again
Hey finally bot gives an error
sure
welcome message is (None,)
a monkey, monkey patching a monkey🐵
oh then .. where is the None var set
Lemme check
await os.exit()
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT welcome FROM wm where guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
if not data:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome) VALUES(?,?,?)", (ctx.guild.id, ctx.channel.id, 'xyz',))
await db.commit()
return await ctx.send(f"Welcome message has been set!")
await cursor.execute("SELECT welcome FROM wm WHERE guild_id = ?", (ctx.guild.id,))
mesg = await cursor.fetchone()
if not mesg: return await ctx.send("There is no welcome message currently set.", delete_after = 10)
return await ctx.send(f"welcome message is {mesg}")``` this is the code idk
!e
import asyncio, os
async def main():
await os._exit(127)
asyncio.run(main())```
@livid hinge :warning: Your eval job has completed with return code 127.
[No output]
while True: await __import__("os").exit()
```😳
Why r u connecting repeatedly? It's gonna error out if there are multiple command invocations at the same time
there's no point, i ve probably said that more than 20 times now
turned out it was _exit
can u help me make it all into one connection
smh
Use a botvar and connect it in setup_hook or smth
told you 5-6 times now
...
privates😔
anyone made a bot that can cooperate with other instances of the bot
shards?
kinda yeah
xd
imagine importing every iteration /s
well discord's shards
sorry sorry
discord has a system which assigns instances of the same bot to certain guilds which those instances are called shards
shards split up the load right? i mean communicate and stuffs
thats the reason pc go boom
like, for example, shutting themself down if another one is running
for a second i believed that it'll exit the program on every iteration
instance detection?
@livid hinge you can probably check the channels history and then check the 2 recent messages and if theyre from the same author in this case the own bot it just logs out of the gateway and then you just connect again
yeah that could work ig
this would only work with 2 instances tho its a hard coded solution imo and theirs probably a better way
i wonder why discord doesnt check the websocket connections
because to make a ws handshake you would need to send an IDENTIFY payload with your bot token so why does discord not save the payload and checks for multiple instances of the same payload
Ok someone ping me if u can help
hmm good question
why not ask here? @warped mirage
Because of AutoShardedBot
wait i thought you needed just one IDENTIFY payload and discord sharded the bot?
we learn new things everyday dont we
k
yas
Hey everyone i need help making my discord bot there's a error w my code and i need some help
How can I rerun the command when the reaction is pressed?
!d discord.ext.commands.Command.invoke
No documentation found for the requested symbol.
Smh
great bot
Can I make a music bot with dpy 2.0 ?
U can but against ToS
wait so how do I do it?
How ?
you'll use something like youtube-dl to download the song which is already breaking youtube tos.
Try looking at the source of that command
.source topic
Smh
.source topic
{
"t":"event",
"d":...
"op":opcode
"s":s
}``` this is what data received from the discord gateway looks like right?
I suppose `"d"` is the event-related payload, but what is `"op"` and `"s"`?
@maiden fable basically @bot.commands() isn't working.
op is the code sent by the Discord API
what's your code so far?
It's bot.command, not commands
is it random?
https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes
@lament mesa
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Yeah ik
This is used for enum purposes, to identify the event
thanks, but what is "s"
import discord
from discord.ext import commands
from discord.ext import task
bot = commands.Bot(command_prefix = "/")
bot = commands.Bot(command_prefix="!")
bot = discord.Client()
@bot.command()
async def ping(ctx):
await ctx.channel.send("pong")
I removed my token btw bc of the server
Oh I realise now there's a error
Why do you have two lines for the prefix?
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Mistake lol
But it still dosent work.
U need that for the RESUME payload
Yo can someone help me please
hmm, i see
The installation is fucked. Reinstall the module
yeah
or remove the third line
It says that now.
I don't even have a Client() so prolly remove that
I reinstalled the command module
So idk 🤷
Nah I mean if someone can help me here fo ping me
Because there’s no point asking all the time
import discord
from discord.ext import commands
from discord.ext import tasks
bot = commands.Bot(command_prefix = "/")
bot = commands.Bot(command_prefix="!")
@bot.command()
async def ping(ctx):
await ctx.channel.send("pong")
@slate swan try that?
Alright
It's tasks not task
and make sure when you run it's like bot.run("token")
that makes sense
@wide tartan do yk about this?
Can you elaborate on what you mean?
when I press the reaction, it will re-run the command (give another topic)
Still not working @wide tartan
Use wait_for
how ?
What's the issue?
Id wait for what though?
Idk tbh im new at this Discord bot programming
When I try !ping in my server no reply.
'reaction'
I add everything back in my token and bot.run("token")
Show your whole file (not the token part though)
Ik
Dont put the token here
Just show the code without the token
reaction = await bot.wait_for("reaction_add", check=check) ?
it would wait how many times?
import discord
from discord.ext import commands
from discord.ext import tasks
#TOKEN would be here
bot = commands.Bot(command_prefix = "/")
bot = commands.Bot(command_prefix="!")
@bot.command()
async def ping(ctx):
await ctx.channel.send("pong")
bot.run("TOKEN")
Idk what the issue is tbh
Unindent the bot.run
Well, do you want it to keep waiting or do you want it to just wait once?
Alr
.
Why do you have 2 bot variables
infinite
Idk I followed some guy on disc who was helping me
I undentited it that's my output
means your bots token is invalid
Make an on_reaction_add event for that then
but I still want it to detect if the eaction is pressed nto added
That event basically detects reactions
so either added or pressed?
Yes
I just reseted it @slate swan and it says the same thing
whats your code now?
Same thing different token.
and does your bot have permission to send messages?
^
Are you sure you put in the new token?
you have to pass a bot token and not a string that says TOKEN
remove one of the bot =
And yes, please dont have 2 bot variables
import discord
from discord.ext import commands
from discord.ext import tasks
bot = commands.Bot(command_prefix = "/")
bot = commands.Bot(command_prefix="!")
@bot.command()
async def ping(ctx):
await ctx.channel.send("pong")
bot.run("token")
Bruh
Hold on
remove either the 5th or 6th line
Hey everyone, anyone used guild.fecth_members? i am trying to capture daily new member joined and total members the server where i am a moderator. i want to store the stats in the db to use it in the dashboard later. thank you!
In the code, you did replace token with your actual token, right
import discord
from discord.ext import commands
from discord.ext import tasks
bot = commands.Bot(command_prefix="!")
@bot.command()
async def ping(ctx):
await ctx.channel.send("pong")
bot.run("token")
Same error
On the bot.run ? @wide tartan
i would recommend you learn basic py and oop and then check out this tutorial https://tutorial.vcokltfre.dev :))
A tutorial to help you make better Discord bots.
@slate swan I know py 100% I'm new to the discord shit
Tf
For on_member_join, you can just store it from the member object. To get every member from the server, do something like this:
for members in guild: # define guild
...```
you know python 100 percent and you cant read a simple traceback?
It's legit 7am and I haven't slept for 12+ hours 🥴 my brain is far gone tbh
doesnt seem healthy does it
What's the error
Yeah ig I'm trying but I need knew meds
Invalid token passed
Who wanna help me make all my aiosqlite connections into one 😉
But it's been reset its not invalid.
Does yr token contain 2 periods?
you can use a bot var or class instance vars and just save the db connection
@maiden fable fixed the token but no input
I also tried on my server too.
Did u invoke the command?
do you have the message intent on?
I would suggest setting an on_ready event printing that it's on so you don't get confused if the bot is actually up or not
first add a onready event to see if bot is starting
also ctx.channel is not required u can just do ctx.send or CTX.reply
Isnt message intents for outside-discord uses related to messages?
@wide tartan has he figured it out yet?
I'm new 😭😭 im trying my hardest rn so hold on
Lemme make sure it's online.
it's all good man, no one is judging
What's the code to make sure it's ready?
Bc i can't find it.
I also haven't slept for 12+ hours 😭
its used for Bot users to read a message's content including embeds and other stuff
Ah, makes sense
@bot.event
async def on_ready():
print("I'm online!")
Here's an example on_ready event. @slate swan
Hello Asher
Idk how lol
I’m on 2.0
dpy version doesn't change the basics of python and OOP
send code.
message.edit(embed=edited_embed)
import discord
from discord.ext import commands
from discord.ext import tasks
@bot.event
async def on_ready():
print("I'm online!")
Put the bot variable
the bot.event has to go under your bot = line
if its not on the gateway will send null as the content inside of the MESSAGE_CREATE payload iirc
What😭
Your bot variable is in the code, right
No.
.
the bot variable is being used before you define it
well, that explains why lol
Send me what it should look like?
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
You basically set the bot variable before
🔄
@slate swan See:
The basic of python:
If you are using a variable to do something (you do: @bot.event), you should define it before using it.
SO, you have to define what is bot.
e.g.:
input
print(dead)
output
Error```
```py
input
dead = "me"
print(dead)
output
me```
Ik how variables work dw
Looked like you dont
If you're not setting a task loop, then tasks is not needed
uh, probably yea
but if he knows python he should've noted that, cus in classes there are familiar @ like @property and else...
i love python decorators ngl
we are here not for spoonfeeding
@wide tartan wait_for("reaction_add") only detected if the reaction was pressed one time
maybe
That's why i told you to use the on_reaction_add event
oh yeah
its literally just ellipsis bro
I haven't slept at all for 12 hours which makes it even funner
then go sleep and then return probably?
doesnt matter how much you slept you cant learn a whole programming language in a day :))
good things take time!
idk how it goes!
I just want this to work then I'll sleep like a baby.
hi
depends on what do you define as "learn a whole programming language", maybe it's just a syntax of lang?
https://paste.pythondiscord.com/zigasaquju.py this is my help cmd code yet the bot dosent show anything and it shows no error
I legit just want to make a command that's it 😭 there was a error which I fixed and now turned into a huge problem 🙃
well then if we go by that logic to learn a whole language like spanish you would just learn its grammar which is quite hard as you dont know what words mean
help Shows this message
Type ?help command for more info on a command.
You can also type ?help category for more info on a category.```
when i run ?help i get this message
well prog. langs and langs are a "bit" different but what do i know 'bout this....
can you plis look in this issue
honestly when someone says they have learnt the language, i would expect them to be able to make basic projects and stuff without having to google everything. Syntax is a small part about a language as pretty much all languages share the same concept
bot.remove_command('help')
just use the kwarg in the bot constructor
can you plis explain in detail
basically it removes the default help command
you could also do help_command=None in the bot constructor like @slate swan said
*put it right after defining a bot to have no problem
just subclass the default help command...
who subclasses the help command at this level
it's more like they even dont know how to subclass
hmm, fair
are you sure your defining your token correctly? or is someone else in your discord account too
wouldn't it do it for all commands if I do it this way?
you need quotes around your token
without quotes
bro put ur bot token in place of "token"
Define the specific message then
😂
send code.
I wanna kms man istg

don't do that
from discord.ext import commands
import discord
token = ("TOKEN HERE")
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("online")
bot.run("token")
:kms:
😂
ah, nitro is gone yeah
it's there in the docs as far as i remember
bot.run(token)
yes
but who reads them tbh
lmao true
xD
honestly subclassing is soo much easier, edit things make super calls and ur done
Some discord shit now
Almost every dpy programmer.
@paper sluice https://paste.pythondiscord.com/zigasaquju.py this is my help cmd code yet the bot dosent show anything and it shows no error
enable the intents in the dev portal
Where's that**
!paste
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.
developer portal
yeah like if u create your own help command and u use group commands or some custom help for a command it's much tougher to co ordinate
ofcourse i dont remember the link\

did u do bot.help_command = HelpCommand() ( u have to import this from the file )
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
the error literally says whats wrong
How do I edit my bot's description using its token?
It now says online but when i try !ping dosent respond @slate swan
@valid panther
I did that (:
is there an error?
You can't.
Shouldn't be.
send your new code
C:\Users\suraj\Music\Discord-Bot-1.3 (1)\Discord-Bot-1.3>python bot.py
File "C:\Users\suraj\Music\Discord-Bot-1.3 (1)\Discord-Bot-1.3\bot.py", line 35
help_command=None
TabError: inconsistent use of tabs and spaces in indentation
C:\Users\suraj\Music\Discord-Bot-1.3 (1)\Discord-Bot-1.3>python bot.py
File "C:\Users\suraj\Music\Discord-Bot-1.3 (1)\Discord-Bot-1.3\bot.py", line 35
help_command=None
^
IndentationError: unindent does not match any outer indentation level
C:\Users\suraj\Music\Discord-Bot-1.3 (1)\Discord-Bot-1.3>python bot.py
File "C:\Users\suraj\Music\Discord-Bot-1.3 (1)\Discord-Bot-1.3\bot.py", line 45
help_command=None
TabError: inconsistent use of tabs and spaces in indentation
is the bot on the server you are using command?
your prefix is $ not a !. try doing $ping @slate swan
from discord.ext import commands
import discord
token ("TOKEN HERE")
bot = commands.Bot(command_prefix='$', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot online!")
bot.run(token)
Anyone?
Is it possible to make our own way using requests or any other library?
@paper sluice
check your indentation
Not while going against the ToS no.
and also try reading tracebacks
put that code in vsc and click format document :p
or any ide ur using
it should have something similar
OMG let’s go
Possible going against TOS?
ryuga how do I check for every reaction press?
Many helpers online lol
error?
@valid panther
We won't help with that.
No error but no response when I try $ping
Sed
there's always this much
is the bot in the server your doing $ping in
That I know *
from discord.ext import commands
import discord
token = ("Token")
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot online!")
bot.run(token)
u make callbacks for things, they get called everytime someone interacts with the ui
Ashley can u help me fix lol
cus there is no ping command
well now your prefix is !, so try doing !ping
no ping command + different prefix
bot.help_command = HelpCommand()
NameError: name 'HelpCommand' is not defined
@paper sluice its giving meh this error
sad
@bot.command()
async def ping(ctx):
await ctx.send('PONG!')``` @slate swan
I tried, await bot.wait_for("reaction_add") but it only checks once
use the class name which subclassed the default help command
import HelpCommand from the file
It's the default value no need to re-define.
dont know
!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.
Still no reply.
[0]
which lib are u using?
version?
You didn't provide much info.
show code
?
maybe you put it in wrong place
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT welcome FROM wm where guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
if not data:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome) VALUES(?,?,?)", (ctx.guild.id, ctx.channel.id, 'xyz',))
await db.commit()
return await ctx.send(f"Welcome message has been set!")
await cursor.execute("SELECT welcome FROM wm WHERE guild_id = ?", (ctx.guild.id,))
mesg = await cursor.fetchone()
if not mesg: return await ctx.send("There is no welcome message currently set.", delete_after = 10)
return await ctx.send(f"welcome message is {mesg}")```
He wants you to index at 0
import discord
token = ("Token here")
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot online!")
bot.run(token)
@bot.command()
async def ping(ctx):
await ctx.send('PONG!')
should i put it below or above cursor.fetchone()
import HelpCommand
ModuleNotFoundError: No module named 'HelpCommand'
i am getting this error now
version 2.0
Lol tbf Ryuga did say that.
poor ryuga
it should be before bot.run(token), not after
!d discord.ext.commands.HelpCommand
class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.
Note
Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).
This means that relying on the state of this class to be the same between command invocations would not work as expected.
put bot.run all the way at the bottom of your code
@slate swan
and?
from discord.ext.commands import HelpCommand
class classname(commands.HelpCommand)
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT welcome FROM wm where guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
if not data:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome) VALUES(?,?,?)", (ctx.guild.id, ctx.channel.id, 'xyz',))
await db.commit()
return await ctx.send(f"Welcome message has been set!")
await cursor.execute("SELECT welcome FROM wm WHERE guild_id = ?", (ctx.guild.id,))
mesg[0]
mesg = await cursor.fetchone()
if not mesg: return await ctx.send("There is no welcome message currently set.", delete_after = 10)
return await ctx.send(f"welcome message is {mesg}")``` is this better
Invalid syntax-
More like from discord.ext.commands import HelpCommand
More like
@paper sluice ?
from discord.ext import menus
class MyMenu(menus.Menu):
async def send_initial_message(self, ctx, channel):
return await channel.send(f'Hello {ctx.author}')
@menus.button('\N{THUMBS UP SIGN}')
async def on_thumbs_up(self, payload):
await self.message.edit(content=f'Thanks {self.ctx.author}!')
@menus.button('\N{THUMBS DOWN SIGN}')
async def on_thumbs_down(self, payload):
await self.message.edit(content=f"That's not nice {self.ctx.author}...")
@menus.button('\N{BLACK SQUARE FOR STOP}\ufe0f')
async def on_stop(self, payload):
self.stop()
# later
@bot.command()
async def menu_example(ctx):
m = MyMenu()
await m.start(ctx)
try out menus then
just put [0] in your f string
'tralala {mesg[0]}'
wtf is this
yeah forgot the class name
class T((__import__("discord").ext.commands.HelpCommand)): 
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot online!")
bot.run(token)
@bot.command()
async def ping(ctx):
await ctx.send('PONG!')
oof
b-b-bye
its just reactions + callbacks. callback is the function that will be called everytime someone interacts with the emoji/reaction
discord has a built-in paginator as well
@slate swan
No reply
put bot.run(token) at the end of file, at the endest end, not in the middle
from discord.ext import commands
import discord
bot = commands.Bot(command_prefix='!', intents=discord.Intents.all())
@bot.event
async def on_ready():
print("bot online!")
@bot.command()
async def ping(ctx):
await ctx.send('PONG!')
bot.run(token)
@slate swan
Oh my days what a difference xd now it just removes the comma welcome message is None
is all that really necessary though?
T=type('',(__import__("discord").ext.commands.HelpCommand,),{...})
its wayy easier to use than wait for, give it a try
Nope @slate swan
lmao ellipsis as class
What how
yes congrats it removed the comma, that's what i helped for, idk what is the data in your db so check it your self, try some microsoft progs to connect into your db and interact with it yourself glhf
No
dms
Xd
Hey Pandabweer
I wonder how much slower a bot would be if you would one-line it completely compared to the same bot non comprehended.
Hello
Wanna help now I guess lol , I managed to get my bot work a bit more
it would be slower but i dont think u would really notice it
Plus the literal maintenance pain and dupe code.
they update lib, whole code base gone
@paper sluice how would I do it without menus?
subclass menus.Menu then add the reactions u want and in the function add the things u want the bot to do after someone clicks the reactions
this would be using menus though?
https://paste.pythondiscord.com/malusomuke error , Welcome message is None
ya? look at the example i sent
I don't get why your code is so long tough, this should only take like <50 lines with cog included.
multguild welcome system
I meant to ask how would I do it without using menus
....
hmm idrk
I was implying that yeah.
someone mentioned on_reaction_add but idk how id do it that way
I first recommend making the cursor globally available by making it either a bot var or by subclassing, i recommend subclassing.
I never subclass tbf I wouldn’t be here if I wouldn’t need help , u know what I mean?
I don’t know how I guess
Okay well then let's subclass it since then programming is a lot easier
And you can use it like commands.Bot
class MyBot(commands.Bot):
pass
I use a cog
In the __init__ method you can define a connection attribute to use everywhere
And I already have commands.bot in my main file
Cogs get the bot instance (so in a cog you would access the connection attribute using self.bot.connection)
Not instantly but I'm trying to make your life easier.
Oh damn so means I gotta restart
Ye idk I need help re building my system if I’m gonna restart
No not likely.
Could you show your main file?
Can I ask why lol
Since then I could show you what subclassing looks like.
I could also use example code.
why in the init and idts that you can run coroutines in the init function
I don’t even know at this point what to do
I just want a simple welcome system for multi guilds
You can assign the attribute the connection in an on_ready event or something, but PEP says to define just the attribute in __init__
noooo
What
not in on_ready

And no one here is really helping right? It's because the code is just really unreadable and unstructured.
setup_hook
Teach me
Just use the setup hook
Ok , then lets start
hmmmm
if if wanted async intialisation and finalisation in cog, would setup() and teardown() be fine?
i see no other async methods for that...
from discord.ext import commands
import aiosqlite
class MyBot(commands.Bot):
db: aiosqlite.Connection
def __init__(self):
super().__init__(...)
async def setup_hook(self):
self.db = await aiosqlite.connect("_.db")
thats how
Cool thanks, will definitely use it.
or maybe __init__ and unload_cog and bot.loop.create_task ?
you can just use a task or overwrite setup_hook with a coroutine
self.db should be inside __init__, no?
The type hinting, I mean
not required
Really? Because there's self
uhhh yes fixed
Well now it's a class variable, not an instance attribute
its just a typehint...
Just put it in the __init__
as you wish
Right, never mind then
i did
self.db: aiosqlite.Connection = await aiosqlite.connect(...)
@slate swan do yk how I can detect every reaction press?
event
mb
!d discord.on_raw_reaction_add
discord.on_raw_reaction_add(payload)```
Called when a message has a reaction added. Unlike [`on_reaction_add()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_reaction_add "discord.on_reaction_add"), this is called regardless of the state of the internal message cache.
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
this will stop after first reaction
How do I make it not stop
@Bot.listen()
async def on_raw_reaction_add(payload):
...
^
but this would listen for all commands?
no?
payload would be what? I dont get it
from __future__ import annotations
import asyncio
from discord import Intents
from discord.ext.commands import Bot
import aiosqlite
class Example(Bot):
db: aiosqlite.Connection
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
async def run(token: str, **kwargs) -> Example:
await super().start(token, **kwargs)
async def setup_hook(self) -> None:
self.db = await aiosqlite.connect("_.db")
async def on_ready(self) -> None:
print("Ready")
bot = Example(command_prefix="!", intents=Intents.all())
asyncio.run(bot.run(TOKEN, reconnect=True))
i mostly dont do this cuz your editor would probably already know the type, but its handy when a value will be mutated
What file is this meant to be ? A cog right ?
Not exactly, this is just making a custom Bot so we can use more variables everywhere.
If you don't want PyCharm to scream at you, you need to add self.db: aiosqlite.Connection | None = None to the __init__ method
I defined db inside the class.
any examples?
its recommended to use start instead of run for v2 now
instead of rewriting the bot at each step u are stuck try to revise the solution to suit your bot instead of bot to suit the solution
I mean it wouldn't make much sense since run is essentially the same in the code atm.
it is, but just saying, it may be deprecated in the future updates
Lemme update it then.
Man each time , first someone says update to 2.0 then subclass ur bot and it goes on
Like what am I meant to have ?!?!
yeah they are all steps to make ur bot not something esoteric
at the end of the day just try to have a working bot ig...
I’ve been stuck on this welcome system for 4 days now lol
@Bot.listen("on_raw_reaction_add")
async def uwu_reaction_listener(payload: discord.RawReactionActionEvent):
''' Called when a message has a reaction added. Unlike on_reaction_add(), this is called regardless of the state of the internal message cache. '''
''' attributes for payload '''
'''
- channel_id: the channel ID which got or lost the reaction
- user_id: The user ID who added the reaction or whose reaction was removed.
- message_id: The message ID that got or lost a reaction.
- guild_id: The guild ID where the reaction got added or removed, if applicable.
- emoji: The custom or unicode emoji being used.
- member: The member who added the reaction. Only available if event_type is REACTION_ADD and the reaction is inside a guild.
- event_type: The event type that triggered this action. Can be REACTION_ADD for reaction addition or REACTION_REMOVE for reaction removal.
'''
@slate swan Does this suffice?
import asyncio
async def main():
async with bot:
await bot.start("token")
asyncio.run(main())```
thats how
ew
well, it is what it is
Okay
I will not comment this 
Lol
why :D_D:
Nah I’m finished
!discord_errors
nah
#bot-commands and what do you need specifically
Damn
so basically i have this code where if the user doesnt specify an amount of messages to purge then it will say please specify an argument
No this is way too ugly I don't understand why they won't just stop using aenter they just chose the easy way out.
you'll have to make an error handler, do you already have one?
yes, there is no error but it just clears when you don't specify an argument
do you want a screenshot of code
lol, no offence but I really find the dpy v2 ugly, even py-cord stands out in that case
Pandabweer: about opening/connecting database in setup_hook ... doesn't it need db.close() somewhere on shutdown?
Anyways back to v 1.7.3 lol
Disnake exists 
use the on_disconnect event in that case...
Do they support WLECOME systems
ah right, thanks
but wait no
Bruh no fork supports a welcome system is something that you will code 
This way of starting is ugly and the fact the programmer needs to sync their own slash commands, it takes a lot of time to code something custom like that and 7/10 programmers don't even know how to make slash commands.
dont dont dont use that event
ok ok
I tried but I can’t
And even if I do no one knows how to fix
Lol
Then you will need to study more because it is simple 
Aiosqlite is not simple
Whoever thinks databases are easy to learn then idk
It's the simplest database 
fr I was planning to make a pr for auto-syncing but I just dropped the idea
It’s not
Try aiogram then 
I was sarcastic .-. aiogram requires more experience than aiosqlite .-.
Ok
oh ok, i got what you're saying
async instagram
from disnake import welcomesys
...
welcomesys.use_db(db_type, db_name, db_host, db_pass)
# or you can use welcomesys.use_json(filename)
welcomesys.start(bot)``` @warped mirage hey! disnake added this in last update, try this out
…..
...
:kyber_mega_ultra_lemao:
jesus
Why did you type hint run to return a bot if there is no return statement inside the method
Ashley, so is there an equivalent of shutdown_hook ?
dont use that kind of language please
I’m so sorry do I get another chance?
yes
✅
your question is about a multi-guild welcome system
Yes that I’ve been working on for the past 4 days
6 hours a day 💀
24 hours and I still haven’t figured out
Is pontifex new? Never seen this man before in my life.
damn
nop
just new pfp ig
Guys how do u even learn how to make all of this … it’s not like docs always show how to make new commands or like systems
Combined stuff.
Brain smaller than -
only if we have one 😔
U guys do
You plan systems for your own bot yourself.
my bot's repo has it-
would this be fine?
async def main():
await open_database()
async with client:
await client.start(TOKEN)
await close_database()
asyncio.run(main())
github, google, and trial and error
Guys how can we take input from user in discord.py
Can anyone tell me with a example
(I searched Google but not understood)
If your only goal is to have a welcome system I don't get why you are messing around with Cogs.
at least, finally authorized for github co-pilot uwu
How much time it took to you? xD
So u want me to have it in a main file ?
a day and a half tops
lol
okay nice, github co-pilot has crashed...
Pls help
github copilot is still in beta no?
whats the controversy about ways of starting
yeah, you have to get authorized to use it
You already broke it 
I think if I had it I would try it for a day then later never use it again.
I just opened VSC lol
still pre-release
same, I prefer using TabNine too
True lmao.
Guys how can we take input from user in discord.py
Can anyone tell me with a example
(I searched Google but not understood)
kite is god-awful
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
Whats useof check?
tabnime reminded me of how bad it was 🤣
function
i don't use any auto completing software...
Bro i asking use
i'm pretty comfortable with copilot tbh
Can someone just help me finish my welcome system or atleast the error
@commands.command(name="example")
async def ex_ample(self, ctx: Context, arg: Any) -> None:
await ctx.send(arg)
oh yeah ^
There is no input tho
Guys does it take a long time to learn most of discord.py honest answers
What do you mean?
Because I wanna be a good coder uknow and not be so crap at all of and have to ask for help so much
You mean input()?
Means this commandd is not taking any input
It is?
Me making pie chart command so i need to use input
input is for console not dpy.
Well if you'll stop loosing time here making commonly questions with the answers placed literally everywhere in the web and with a pretty good knowledge of python itself you can learn it in about a pair of week
!command input thats the input...
Means i asking how to use input in dpy
No way lmao ur serious ?
I learned it in a week..
First Learn python......
Ok I’ll take ur advice and I’ll see how I do
We're pretty knowledgeable ;-;
A day 
Learn the language before using its library
resp = await client.wait_for("message")
''' if resp gets the response in time, it will return a Message object '''
''' timeout '''
import asyncio
try:
resp = await client.wait_for("message", timeout=seconds)
except asyncio.TimeoutError:
await ctx.send("no")
finally:
do_uwu_stuff_if_you_like()
''' check '''
def check(msg):
return msg.author.id == ctx.author.id and msg.channel.id == ctx.channel.id
resp = await client.wait_for("message", check=check) #this will only return the message which meets the proper requirements
''' combined '''
try:
resp = await client.wait_for("message", check=check, timeout=69)
except asyncio.TimeoutError:
return await ctx.send("uwu")
if you want the input to be a message
What did it cost?
Ty mee read it
why did I write all that
A half year experience in PHP coding and my soul.
lmao
Can I use while loop in it?
you can but it will be blocking
Then for loop?
while True:
I want to take input 5 times so I'll be using while
Lol you can't
uwu
for x in range(10):
while True:
fuck, github co-pilot is the shittiest software i've seen
i have a question, if i have commands.CommandInvokeError as an error handler, do i need Member/Role/ChannelNotFound handlers?
from discord.ext.commands import Greedy
@commands.command(name="example")
async def ex_ample(self, ctx: Context, args: Greedy[str]) -> None:
await ctx.send(arg)
*args?
@commands.command(name="example")
async def ex_ample(self, ctx: Context, *, args) -> None:
await ctx.send(arg)
No? That's not how greedy works :x
@warped mirage flex 😔
i know lol
H
That’s nice for you
returning ctx.send?
ikr
And unlucky for me
yeah there's more to the function
umm anyone?
Bruh now I can’t even make the system
no comments
you could still refer to mine, its not the best, its not the worst
Didn’t ask for comments lol
never made a comment...
Ye but yours is weird and u only show the db . Like u do from Future import something idk I don’t make this type of stuff
show db? the repo is public....
Yeah it's the base exception, I also recommend getting the original error if possible.
U don’t show the actual codes
how is future related to this in any way??
file names starting with a capital letter.
Hikari tho
totally me
Oh my days why am I so unlucky
Duh weirds
Package starts with capital
idk, I have a bad habit of doing that cuz I generally name my react.js files with capital letters, stop humiliating me for no reason 😔
Uh i didn't want to 
im trying to minimise the number of error handlers i have.. so i was thinking to put CommandInvokeError and remove the NotFound types
well......sqlite is completely unrelated to hikari
Well they are there for a reason so I don't recommend ignoring them.
hikari requires more knowledge than d.py
bet
Rip
bet
Finished ones again
hmm okay thanks
@plugin.command
@lightbulb.option(name="query", description="The subject to search for!", type=str, required=True)
@lightbulb.command(name="news", description="...", auto_defer=True, ephemeral=True)
@lightbulb.implements(lightbulb.PrefixCommand)
async def news_command(ctx: lightbulb.SlashContext):
...
@Bot.command(name=..., description=...)
async def news_command(ctx: commands.Context, query: str):
...
huge difference
and the fact that you dont necessarily have to use classes for extensions
But you are comparing a slash command to a message command... the dpy slash command also have 1000 deco's
Disnake has only one 
its a prefix command.
on_message command.
wdym?
nice fork but forks bad
Bot is just an advanced on_message bot lmao.
I know....
Duh disnake is better than d.py
not really, in terms of simplicity, yes
dpy just needs to fix small issues. Then it's good
Like not needing to pass Intents since you can have no intents and auto sync + better cogs for slash cmds.
this kills me tbh
agreed
This is how I load "cogs" in a Client bot for slash cmd's ```py
import importlib
import inspect
import pkgutil
from typing import Iterator, NoReturn
import exts
from discord.app_commands import Group
def unqualify(name: str) -> str:
"""Return an unqualified name given a qualified module/package name."""
return name.rsplit(".", maxsplit=1)[-1]
def walk_extensions() -> Iterator[str]:
"""Yield extension objects from the exts subpackage."""
def on_error(err_name: str) -> NoReturn:
raise ImportError(name=err_name) # pragma: no cover
for module in pkgutil.walk_packages(exts.__path__, f"{exts.__name__}.", onerror=on_error):
if unqualify(module.name).startswith("_"):
# Ignore module/package names starting with an underscore.
continue
if module.ispkg:
imported = importlib.import_module(module.name)
for name, obj in inspect.getmembers(imported):
if inspect.isclass(obj) and issubclass(obj, Group):
yield obj
EXTENSIONS = frozenset(walk_extensions())
Can someone help me with my error
too much brain application
Sure.
error ie?
Welcome message is not None 😈
I still need to do auto asyncing but i'm not coding bots in dpy rn.
which lib then?
preferably*
wha-
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
jeez
I'm making an android app 😂
lol yeah I understood, better use flutter though
Isn't flutter the wordpress android version?
no?
StringRequest earthquakeRequestInduced = new StringRequest(Request.Method.GET,
"https://cdn.knmi.nl/knmi/map/page/seismologie/all_induced.json",
resp -> {
induced = gson.fromJson(resp, EarthquackeDataNetherlands.class);
for (Event item: induced.events) {
if (item.place.equals(parsed_data.name)) {
Log.w(TAG, "Found quacke");
}
}
}, error -> Log.w(TAG, "Error while getting NL induced earthquakes" + error));
``` besides who doesn't want this.
If you look at it correctly you can see that this is a single class definition.
cant argue, seems handsome
Lol
You too
no u
sheesh
:3
@commands.command(aliases=['bal'])
async def balance(self,ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f'{ctx.author.name} Balance',
color=discord.Color.red())
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name='Bank', value=bank_amt)
await ctx.send(embed=em)
if a users id is not there in mainbank.json how to i make the bot send this message you need to start
from matplotlib import pyplot as plt
import numpy as np
nov = int(input("enter number of values"))
initial = 1
cars = []
while initial<=nov:
print("enter the value to append")
apen = input()
cars.append(apen)
initial = int(initial+1)
nop = int(input("enter number of values for pie chart"))
initials = 1
data = []
while initials<=nop:
print("enter the value of pie chart to append")
apens = int(input())
data.append(apens)
initials = int(initials+1)
fig = plt.figure(figsize =(10, 7))
plt.pie(data, labels = cars)
plt.savefig("chart.png")
Can anyone help me covert this into discord command?
@commands.command(aliases=['bal'])
async def balance(self,ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
if not str(user.id) in users:
return await ctx.send("Not found")
wallet_amt = users[str(user.id)]["wallet"]
bank_amt = users[str(user.id)]["bank"]
em = discord.Embed(title=f'{ctx.author.name} Balance',
color=discord.Color.red())
em.add_field(name="Wallet", value=wallet_amt)
em.add_field(name='Bank', value=bank_amt)
await ctx.send(embed=em)
Can anyone help me pls
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
I mean, he wants help converting it into a command?
didnt read
the exact same thing in a command and you send the image with the send method 
and take input from the command arguments, not from the console
this is a bit trickier, though, since you have a varying number of values ...
can still be done, though. a command that takes multiline input.
or maybe just two arguments, each of which is a comma-delimited list, then convert those to lists before passing to pyplot
await ctx.command.invoke(ctx)
File "/home/runner/Alpha/venv/lib/python3.8/site-packages/disnake/ext/commands/core.py", line 914, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Alpha/venv/lib/python3.8/site-packages/disnake/ext/commands/core.py", line 181, in wrapped
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'User' object has no attribute 'add_role'
getting this error pls help me
gg = await ctx.guild.create_role(name = "Alpha.Beta",colour =0x206694 )
await gg.edit(position = ctx.guild.me.top_role.position-1)
await ctx.send("Done......")
await c.add_role(gg)```
c = client.get_user(980705483566493706)
ASHLEY
Hiiii
What are you doing right now
Lol you sleep in the morning?
Oh bruh
Its probably add_roles
Its 12 pm for me currently
nah, I didnt sleep at night
two nights specifically
- Role can only be added to
Member - It's
add_rolesnotadd_role
i have a color in hex value in string '#ffffff' how do i get color from this in embed
How to host discord bot for free 24x7
color in embed can be only rgb or hsv
U can do 0xFFFFFF
No
ok lemme try
I use 0x codes
Maybe with the row value?
Hahaha the name is Hunter not setattr
lmao well then thx hunter
Guys will bot.wait_got work in cogs?
yeah it will
where is the check it will give check not defined
Oh
How to fix this error?
u have to make a check
OoO
u could just put all cogs in a folder then load it at once
i cant await it
Hey I ahve a easy way
commando. is a part of your file name?
cogs = ["cogs.invite","cogs.quote","cogs.wanted","cogs.purge","cogs.pot","cogs.image","cogs.spotify","cogs.channel","cogs.anime"]
@bot.event
async def on_ready():
print("The bot is ready!")
print("Loading cogs . . .")
for cog in cogs:
try:
await bot.load_extension(cog)
print(cog + " was loaded.")
except Exception as e:
print(e)
I use this way you can try it
do this ur files as i see is in a relative path so u need commando/xyz
yeah u shouldnt
@shrewd apex can you help me
I am getting indentation error even it's correct
ur cogs load after bot loads
thats not the problem
while...
indent ur while and await one more time
dont load with command either
Still
do
async main():
async with bot:
await bot.load_extension('xyz')
await bot.start(token)
asyncio.run(main())
ok
where do i do it tho
in the end u can just copy paste
ok
Do you have solution from it?
ur load extensions in the async with bot part
can i see the error in the image what can i see or understand from that
yeah
and i remove the last line?
u cant mix tabs and spaces when indenting
Hmm
read the error before asking first
Me on mobile no tab :(
hmm lemme see mine
ok
import asyncio
async def main():
async with bot:
await bot.load_extension(...)
await bot.start("token") #use this function instead of "bot.run()"
asyncio.run(main())
```?
thats strange
@shrewd apex i did all indents correct still it shows
are all the cog names correct?
My?
no
yes
u have some tabs mixed fix them
from discord.ext import commands
import discord
from progress.stats import *
class Area(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.cooldown(1, 1, commands.BucketType.user)
async def area(self, ctx, arg: int):
try:
stats = Stats(ctx)
if 1 <= arg <= 14:
if arg <= stats.highestArea:
db[stats.userid + 'area'] = arg
await ctx.send(f'**{ctx.author.name}** has moved to **AREA {arg}**')
else:
await ctx.send(f'**{ctx.author.name}** fight more bosses to unlock this area :D')
else:
await ctx.send('404 area not found')
except KeyError: #error handler
await ctx.send(f'**{ctx.author.name}**, your account is either not created yet or not at the latest version. Try using `rpm start`')
def setup(bot):
bot.add_cog(Area(bot))
```this is one of my cogs
is it correct?
async def load():
for filename in os.listdir("./commando"):
if filename.endswith(".py"):
await client.load_extension(f'commando.{filename[:-3]}')
async def main():
async with bot:
await load()
await bot.start("token") #use this function instead of "bot.run()"
asyncio.run(main())
huh ok
do this and load your cogs
async def load():
for filename in os.listdir("./commando"):
if filename.endswith(".py"):
await client.load_extension(f'commando.{filename[:-3]}')
```copy pasta this?
@shrewd apex
yeah
!paste
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.
