#discord-bots
1 messages ยท Page 804 of 1
Traceback (most recent call last):
File "D:\Python\lib\site-packages\discord\ext\commands\core.py", line 179, in wrapped
ret = await coro(*args, **kwargs)
File "d:\Coding Playground\Python\cwlbot\bot.py", line 191, in testing
row = reps_sheet.find(tag).row #getting row no
AttributeError: 'NoneType' object has no attribute 'row'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\Python\lib\site-packages\discord\ext\commands\bot.py", line 335, in invoke
await ctx.command.invoke(ctx)
File "D:\Python\lib\site-packages\discord\ext\commands\core.py", line 916, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "D:\Python\lib\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: AttributeError: 'NoneType' object has no attribute 'row'
but the tag i am passing in as argument is in the sheet
i am sorry for this spam but i am not find this is not working... it is really pissing me off lol
someone knows what might me causing ths?
im making a module for making discord.py more easy
reps_sheet.find(tag) is apparently returning None
well the error is not there in the code you shared
umm yea i think the same
getting this error. raise errors.ExtensionNotFound(name)
discord.ext.commands.errors.ExtensionNotFound: Extension 'somecommands' could not be loaded.
I use my brain to interpret python... normal interpreter is just too boring
Hosting a discord bot using cognitive technologies would be fun
Is the somecommands.py file in the same directory with bot.py and is it your project's root one?
yes both in the same folder
And your root folder is that
Used in event as a check for commands to work properly
Afaik first the message goes to on_message event, then if you use process_commands on its context, its content will be checked if it is a command
And the corresponding function will be executed if there's such
you can just use .listen() instead of .event
on_message
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.9)").
Example...
There's a different decorator for using them in cogs
you can use that anywhere, but for cogs its different
!d discord.ext.commands.Cog.listener
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
Yeah depends on your case
If it's not in cog, use listen, if it is, then commands.Cog.listener
Technically, you can put it to anywhere, but usually main.py only contains bot class and its runner
ok. main.py is different than a cog file. In cogs you use commands.Bot.listener() and in main.py you can either use bot.event or bot.listen(), the reason i said bot.listen() is better than bot.event because you dont have to do the extra work and is more convenient
bot.listen doesn't override the previous event callback
You only use commands.Cog.listener in a cog class because you don't have access to bot before the Cog is constructed
It's simply a marker, you'd use bot.listen where you have access to bot, you'd use commands.Cog.listener as a marker for places where you cannot
bot.event overrides the library's event itself, while bot.listen stacks over it. Simple as that.
commands.Cog.listener is just a version of bot.listen
Straight forward as I can get, It doesn't override previous implementations
The previous implementation
If you use bot.event all previous implementations get wiped and it uses the new one you provided
For an example, with the commands extension. on_message has a default implementation
They hook onto on_message and process any commands with the parser, etc
If you use bot.event it overrides that with your new implemenation
I was just writing that out
I'll send it anyway
For example: when you use bot.event for on_message, it overwrites the lib's ability to process commands. Therefore you have to include await bot.process_commands at the end of it.
When you use bot.listen, is just stacks on the lib's event - it just adds onto it, doesn't overwrite it
Yes.
In laymen terms, yes
event clears ALL, Listeners keep default and keep any previous implementations you've made
It's literally just any new callback you set
No example is needed, just think about listener == no override
you just change the decorator from event to listen()
or Cog.listener() if in a Cog class
https://github.com/DisnakeDev/disnake/blob/v2.3.0/disnake/ext/commands/bot_base.py#L600-L601 - this is the default on_message event built into the library. When you create a bot.event, this will be overwritten
disnake/ext/commands/bot_base.py lines 600 to 601
async def on_message(self, message):
await self.process_commands(message)```
When you use bot.listen, it'll not remove this, just stack on top of it
event overrides the defaults, listen doesnt
^ can't make it simpler than that
Prefer listeners over events, you can have multiple different listeners listening for the same event, but you can't do the same with events. Also too many people use on_message event for some reason (youtube tutorial maybe?) then none of their commands work.
that's happened too many times to count
You don't need on_message
commands.comand is not an event
^ it's how you make commands within a cog
so weird comparsion
I think i get what he's saying
If you have command handlers there shouldn't be a need for on_message, is that what you're saying?
Don't get me wrong, on_message event does have some neat benifits
debug
For example, if you wanted to ignore all messages from bots:
@bot.event
async def on_message(message: discord.Message):
if message.author.bot:
return
bot.process_commands(message)
You could do the same with checks but I prefer this
Also if you wanted to have a feature where you have blacklisted users in a database
We could check if a message came from those users using on_message?
I just use a check for that
@sick birchor if you want to have your costume messages for when boosting server etc, message.type
@bot.event
async def on_message(message: discord.Message):
blacklisted_users = # get users from database
if message.author.id in blacklisted_users:
return
bot.process_commands(message)
yep that too
No since that would still pass the message onto the command handler
Nope
commands would not work
but it tells you in doc, if i remember correct that they recommend use listeners
Yes, if blacklisted_users is a list of IDs who cannot use the bot, then any of those users will not be able to use the bot (bot will not respond at all)
Yep
It sort of acts like a gateway, that says what gets through to the command handlers and what gets dropped
Much harder yes
Well, on_interaction perhaps
but you can make a costume decoration check tho?
global checks don't work on slash commands do they?
Not for discord.py
@if_blacklisted
costume?
Maybe the forks have that working, don't use forks wouldn't know
custom
Oh
thanks robin ๐
^ but yes you can make a custom decorator check as well
i always mix costum and custom
they would both effectively do the same thing, i just prefer this since it's more straightforward
i have this code to make a ticket transcript after closing a ticket
fileName = f"{ctx.channel.name}-transcript.txt"
with open(fileName, "w") as file:
async for msg in ctx.channel.history(limit=None):
file.write(f"{msg.created_at} - {msg.author.display_name}: {msg.clean_content}\n")
await ctx.channel.delete()
ticketIds.remove(channelId)
print(ticketIds)
save_id()
and it gives me this
2022-02-05 16:57:39.978000 - Lord Cringey: $close
2022-02-05 16:56:13.451000 - Lord Cringey: Nothing happened
2022-02-05 16:56:10.380000 - Lord Cringey: As if
2022-02-05 16:56:08.040000 - Lord Cringey: So go about on ur day
2022-02-05 16:55:57.706000 - Lord Cringey: Just testing smth
2022-02-05 16:55:47.166000 - HC Utilities:
2022-02-05 16:55:46.648000 - HC Utilities: @Lord Cringey @Staff
how would i make it so that the earlier msgs are at the top of the file and not at the bottom
Anytime ๐
one way could be put seek in or something @dire folio
why my list isnt updating?
seek(0)
pass in the oldest_first boolean
oh u even had that help ^
async for msg in ctx.channel.history(..., oldest_first=True, ...):
...
ty
is mysql a good database to use with discord.py?
Any database is good
also how would i round the time so it isn't so exact
Personally the way I like to deal with databases is have a seperate API server, written in Express.js, which uses Prisma or TypeORM to interact with the database. Then in discord.py, you would use aiohttp to interact with the database.
i could recommend aiosqlite if you dont need remote database
But of course to do that you'd need to know a bit of javascript
I think that heeds to the separation of concerns philosophy
i use sqlite3
what u mean? round(unixtime?)
round()
consider use aiosqlite instead
you can also just int() it
you can also do str(time).split(".")[0] kek
I think int() is more accurate. Say the UNIX timestamp says 2.518528, if you use round(), it would be 3, except you're still in the 2nd second, not the 3rd. int() would just return 2, which is accurate since you're in the 2nd second and not the 3rd
if that makes sense
Either way you'd be off by only a second but if you really need that accuracy use int() rather than round()
@sick birchthats true, round is round
the accuracy doesn't matter too much
You can also do math.floor(2.5827) which is the same thing as int()
i think most uses round atleast what iv seen
if moneyprice round would be more accurate than int ๐
isnt int() also slightly inaccurate then?
Well it indicates the time better, since it doesn't round up
cant you tell round to round down tho?
Hey any hosting recommendations for free (or cheap ones) that are reliable
Ah ha, this is why they round down instead of up in banks. If you earn, say 2.555 cents from interest, they will give you 2.55 rather than 2.56 to save that half a cent
AWS has a free tier
thanks appreciated ๐
haha getting scammed
You can chain except statements:
try:
# something
except error1:
# print error1
except error2:
# print error2
except error3:
# print error3
Not really, if they rounded normally the banks would be losing money
You can do one of 2 things:
i) remove all try/excepts and stress test your code, and see all the possible errors that could happen
ii) go searching around documents for all functions that you use and see what errors they can throw
Tbh I would love to see someone make an economics bot yk
you can even put an else: in try
For example, say you had await ctx.send(...) in your try block, according to the documentation, it can raise 1 of 3 errors:
i) HTTPException
ii) Forbidden
iii) InvalidArgument
You can chain 3 except statements for each of these, and do something according to those errors
Is there a timeout command for discord.py?
You'd have to use a fork or implement it yourself
I guess at times it will just look more accurate then
ohh yikes alright thanks tho
why are you getting the guild? member.guild returns the guild object iirc...?
you can just do server = member.guild
Yeah member.guild returns the guild they just left
and you can leave out the user since it's just re-getting it
or do user = member if you want to
I just found it strange you used the guild object's id attribute to get the guild object kekw
it happens
especially with newbs like me
and if you're looking for a channel named general, easiest way would be to use utils.get() rather than find
you don't need to use lambda for that
Lol
But yeah I don't really think there's a better way of doing what you have right now without changing the way it works (user defined join/leave channel)
maybe use elif and save on all returns
would that really make it cleaner though?
last return has nothing impact aslong u dont have more codes belows it
you wont need the returns in every ifstate if used elif
from discord.ext import commands
from dotenv import load_dotenv
from os import getenv
import discord
load_dotenv() # You can pass the location of the .env file if it's not in a standard location
token = getenv("DISCORD_TOKEN")
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!")
bot.load_extension("somecommands") # Note, we don't need the .py file extension
bot.run(token)
from discord.ext import commands # Again, we need this imported
import discord
import time
from datetime import datetime
class SomeCommands(commands.Cog):
"""A couple of simple commands."""
def __init__(self, bot: commands.Bot):
self.bot = bot
self.last_msg = None
# Embded message command shows the embded info
@commands.command()
@commands.has_role("Admin")
async def hello(self, ctx: commands.Context, productname):
embed = discord.Embed(title=test, url="https://test.com", colour=0x87CEEB, timestamp=datetime.utcnow())
embed.set_author(name="something", icon_url="https://avatars.githubusercontent.com/u/16879430")
embed.add_field(name="Field 3", value="Look I'm inline with field 2!", inline=True)
embed.set_footer(text="Powered by United Digital Company!", icon_url="https://cdn.discordapp.com/emojis/754736642761424986.png")
await ctx.send(embed=embed)
def setup(bot: commands.Bot):
bot.add_cog(SomeCommands(bot))
import bot
from somecommands import SomeCommands, hello
text = ("Hello world!")
if "equal" == "equal":
sent = hello(text)
sent()
In the call.py i would like to call the function in somecommands to sent a embded message. And use the variable from call.py
No you can use elifs and get rid of the returns
if a==1:
...
if a===2:
....
better with ```py
if a == 1:
...
elif a == 2:
...
else:
...
kinda but u can skip else if no need
else will be if any other statement above matched it will be executed
huh?
pls help i have error in my bot music cmd
it's all the same and subjective, some people like to use returns some like if/elifs. they do the same thing
We can't help with music bots as it breaks TOS, sorry
An error occurred: Command raised an exception: ClientException: ffmpeg was not found.```
def func(num: int) -> bool:
if num == 0:
return False
return True
``` this is much better than using `elif`
if server.system_channel:
await server.system_channel.send(msg)
return
general = find(lambda x: x.name == 'general', server.text_channels)
if general and general.permissions_for(server.me).send_messages:
await general.send(msg)
return
backup = server.text_channels[0]
if backup and backup.permissions_for(server.me).send_messages:
await backup.send(msg)
return
return
if server.system_channel:
await server.system_channel.send(msg)
general = find(lambda x: x.name == 'general', server.text_channels)
elif general and general.permissions_for(server.me).send_messages:
await general.send(msg)
backup = server.text_channels[0]
elif backup and backup.permissions_for(server.me).send_messages:
await backup.send(msg)
you can just do return await backup.send(msg)
but that general variable should be run first
if server.system_channel:
return await server.system_channel.send(msg)
general = find(lambda x: x.name == 'general', server.text_channels)
if general and general.permissions_for(server.me).send_messages:
return await general.send(msg)
backup = server.text_channels[0]
if backup and backup.permissions_for(server.me).send_messages:
return await backup.send(msg)
yeah that could work too
i guess its a taste decision
that one does look clear n easy to read
oh well atleast we teached him elif ๐
if, elif, else is what exists
how would i increase the font size when typing into a file
i meant like with the bot
u cant edit fontsize?
cause i need it to right into a file
am lil bit confused
nvm
either I'm not understanding your question or you are using Microsoft Word
tbh there should hardly ever be a reason to use elif
not really
yes really
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
it would be ugly with only ifstates n not have a elif - and u missing out else
if a == b:
...
elif a == c:
...
else:
....
vs
if a == b:
...
if a == c:
...
``` now u have no else
actually I know of a case when the purpose of the second one fails
Suppose u r doing it in an error handler and the command is raising both HTTPException and ChannelNotReadable due to any reason. Then both the if statements will execute
Happened with me a few months ago
You would fix that by using isinstance
Doesn't make sense eitherway to check if an instance is another instance with == anyways
You'd use is
I did
If I remember correct, it still errored out
yeah if you didnt use elif
That's odd HTTPException and ChannelNotReadable are two different classes, they shouldn't have been able to both enter
Just an example
but also one error is an error
when u fix first it would land on elif is error there
but i can see if u use only if it will hint both errors
oh well if no returns ๐
does py3 have case match yet?
Let's say I have a command that automatically sends a message to a channel at a certain time interval, and when the user sends the word I want to the channel, how can I stop the command without restarting the bot?
you can basicly make a a varaible you can give true of false
and have that send message function check if that var is true or false first
3.10
like .announcement (will turn False if var is True, and True if False)
and ur automaticly event, checks that var
that way u can turn off n on
ah am only on 3.9 ^^
Yeah it is possible but i mean if i do that;
if message.author.id == authorid and message.content == msg:
break
is this works?
@maiden fablekinda weird tho why so late with it when C/C++ and php all had it centries ago
python moment
Idk
If you really want you can make your own case and match with a class implementing __exit__ and __enter__ along with __call__
Should be fairly easy to do
or u can just do if and ifelse ๐
just wondering why taken so long time to get that
my discord bot looks like it processes one message at a time, it does not want to process stuff in parallel. is there some super easy way to make it process messages in parallel?
@client.event
async def on_message(message):
if message.author == client.user:
return
elif message.content.startswith('!something'):
query = message.content
response = f(query)
await message.channel.send(response)
process_command()
right now it will wait for all the queued messages to be fully answered before it dumps all the queued responses at once. so it is inefficient and waste of time
i don't get it
you mean me?
@strong vesselyeah if u put await process_commands(message) at end of ur on_message
but that usally needed to process commands, i dont know what ur issue is about it should be asyncronised
ok
do u mean command snot working?
i mean if it suddenly dump 10 messages on it, instead of doing it all in parallel, it would queue the 10 messages, processing 1,2,3,4,5 ... 10 in sequence one by one, and then it would dump the 10 responses (5 messages/5seconds) to the user
what i want is for it to try everything in parallel not in sequence, and of course not to wait for previous things to be done
your on_message clogging up perhaps
try learn make commands. esp cogs and skip use startwith in on_message for commands
as i said sounds like you clogging it up
use the commands extension
or mixing nonasyncronized libs n codes with asyncronized (discord)
even if u make a command that is not asyncronized it will act same as for u now clogging up
i think its definitely my discord logic that is forcing synchronous
since i checked the other aspects and they are fully parallel/async
if you block the event loop discord.py won't be able to heartbeat to the gateway and you're gonna get disconnected
@strong vesseltheres plently of examples of basic bot structure with cogs n commands
I have this for a ticket transcript
cday = datetime.now().strftime('%a')
cdate = date.today().strftime("%b %d, %Y")
ctime = datetime.now().strftime("%H:%M:%S")
current = f'{cday} {cdate} {ctime} '
if channelId in ticketIds:
fileName = f"{ctx.channel.name}-transcript.txt"
with open(fileName, "w") as file:
file.write(f"Ticket Name: {ctx.channel.name}\n\n")
async for msg in ctx.channel.history(limit=None, oldest_first=True):
file.write(f"{msg.author.display_name} >>> {msg.clean_content}\n")
file.write('\n')
num = num + 1
file.write(f'Generated by HC Utilites\nTime: {current} GMT+0000\n(Greenwich Mean Time)\nNumber of messages: {num}')
how would i make it so if a message is an embed it will write Message cannot be displayed to the file
@strong vesselnothing is cringe being new.
what should be used instead?
oh i guess process command
process_commands() only passes it throu, but what uu should is make commands as methods
Use the commands.Bot class instead of discord.Client
it allows you to make commands with Functions
and its way more effeciant than read line by line and execute ifstatements in on_message
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Anyone knows how sent embeded message from the call.py?
https://tutorial.vcokltfre.dev/tutorial/05-cogs/ check this out
Cogs are a very important part of discord.py which allow you to organise your commands into groups - not to be confused with actual command groups, which will be explained later in the tutorial.
thats why I sent the cog tutorial lmao
also this looks beoken af, if "equal" == ""equal:
cursed
its equal
tonny what are u tyring to do
u wanna send an emebed from a new file?
why dont u send it in ur cog that u already has
i am so confused man maybe u thinking wrong of what u wanna do
what u can do is in ur cog, is import ur functions from the file
and have it return
into your cog calling ur functions
yo how do you incorporate your python code into a discord bot
What do you mean?
like how do you write your code into a bot
@final ironi guess its saturday ๐
I have another function in call.py i just like to pass the variables from the function to sent an embeded message to discord
what code?
You just add it in
how though
ctrl+c ctrl+v
well no duh but where do you go to create a bot
u want like
# your cog
from myfunctions import thisfunction
async def():
m = thisfunction(1, 5)
await ctx.send(m)
``` ?
hmm let me try
Check this tutorial out https://vcokltfre.dev
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
Takes you through the entire process
so which is the best fork for dpy now?disnake?
you open up notepad.exe?
in your editor
based if someone makes a fax-machine that can take writting n scans n return code
handwritten bot
litterly
Repl.it is a simple yet powerful offline IDE, Editor, Compiler, Interpreter, and REPL. Code, compile, run, and host in 50+ programming languages: Clojure, Haskell, Kotlin (beta), QBasic, Forth, LOLCODE, BrainF, Emoticon, Bloop, Unlambda, JavaScript, CoffeeScript, Scheme, APL, Lua, Python 2.7, Ruby, Roy, Python, Nodejs, Go, C++, C, C#, F#, HTML, ...
make sure to put settings in folder (windows) show file extantions and name em .py
and is it worth switching if you already have a bot
it is you get slash commands timeout and others
just use find and replace which most editors have and replace the name space discord to disnake or import disnake as discord
I use nextcord
make your bot a public bot
what editor do you guys use
in discord devportal
it auto adds after i set this?
yes
okay thank you
in general?
yes
VSC and VS
well i use vscode
should i use vs code instead of pycharm
ill say yes
I am not very good at the terminal tho
Depends what you're looking for
for discord bots I don't think there's a need of pycharm tbh
Pycharm is a full on ide while vscode is more of a text editor
I would say vscode is kinda pseudo-ide tbh
hmm, then its ur choice, u can try both of them, whichever u like, u choose and continue
I'm looking for an editor that allows you to install packages and moduels without anyproblems
both vscode and pycharm are nice
ok
Just use a virtual environment and you can use any editor
its in general in ddocs
ok, thank you
@commands.Cog.listener()
async def on_message(self, message):
guild = message.guild
if message.content == "citizenship":
#all citizenships citizenships
role1 = guild.get_role(938834958124978247)
role2 = guild.get_role(938834984515555458)
#
list_of_roles=[role1, role2]
citizenship=random.choice(list_of_roles)
#gce = grant citizenship embed
gce=discord.Embed(title="Congratulations", description=f"You have been granted {citizenship.mention} citizenship", color=0x4da917)
citizenshipdenied=discord.Embed(title="Sorry for the inconvenience!", description=f"This has been caused due to you already possessing {role1} citizenship.", color=0xff0000)
citizenshipdenied1=discord.Embed(title="Sorry for the inconvenience!", description=f"This has been caused due to you already possessing {role2} citizenship.", color=0xff0000)
if role1 in message.author.roles:
return await message.channel.send(embed=citizenshipdenied)
elif role2 in message.author.roles:
return await message.channel.send(embed=citizenshipdenied1)
else:
await message.author.add_roles(citizenship)
await message.channel.send(embed=gce)```
Yhis was working not even yesterday
Today it isn't working anymore. How.
The call.py is a scrapy spider which iterates. When it matches something it need to use the variables scraped from the spider and sent it to discord embeded
Is this supposed to be a command?
Can someyeone help me? When i make a discord bot, or even copy the code (not forgeting to change the token) it Just doesnt do antthing, i whatched some tuturials but they Just al say that it must to work? I use pycode btw.
If you are new to python, I recommend to begin with smaller projects first
can you show the whole code
!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.
read this and paste your code in the link โ๏ธ
don't watch tutorials, they're bad & outdated
and discord.py is not beginner friendly, you need to have a firm understanding of the language before you use the library
^
beginners find learning from tutorials rather easy than slamming their head on the docs
instead tell them to not watch outdated tutorials
but then just copy code?
you can copy code from docs too
Then they get misinformed and have to re-learn the right way to create code
it's not the same
The docs gives you the functions and what said arguments are so you can use them for yourself
itโs not a whole bot that they give you
I am just saying that docs don't suit people who are just getting into coding
Copying code won't teach you anything unless you understand what does each line of that code do
stackoverflow
Yeah, that's why python discord bot is not a good beginner project
it is.
Import discord
TOKEN = "the token"
client = discord.Client()
@client.event
async def on_ready()
print("logged in") #this doesnt even halen
client.run(TOKEN)
no it ainโt lmfao
lmfao
is this your whole code?
Client 
No but the part that doesnt work
everyone knows you use bot over client๐ฟ
@fresh steppe we strongly recommend you to learn some basics of python, it will be much better for you. We can fix this code of course, but this won't give you any knowledge and you will not be able to make one by yourself
^
does it throw an indentation error?
Lmfao
Lol
he makes nukes on the daily
on the flow dude, daily what
๐
Ok i wil look on some simpler projects
Yeah
learn python first-
I rewrote my code but it still does not run in parallel. It waits for every received message to be done before dumping them all at once to the users.
from discord.ext.commands import Bot
bot = Bot("!something")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
else:
query = message.content
response = f(query)
await message.channel.send(response)
await bot.process_commands(message)
how to make it run in parallel? and to send the response the moment it is done instead of waiting for all the others to be done?
like how to make every message immediately start processing, and then respond as quickly as it is done, never waiting
What ever f is, it isn't allowing for concurrency
You probably have a bunch of blocking code in there
It's just requests.request
That's blocking
๐ณ
You should be using aiohttp
How do I make my own bot go online
oh no
Aiohttp good ๐
wow i hope this works
in england โon the dailyโ just means โon a daily basisโ
i remember when i thought this was #bot-commands and i posted a command here and everyone was like "i hate you go to hell"
i kinda started my "journey" with a discord bot too, though, i pretty much had the minimum knowledge about python or coding in general, all my "commands" where if message.content.startswith 
I know smhh, I meant something else
How do I get my bot to be online
you run it
This is your first message in this channel
LOL
Mhm
pov: you're yandre dev
relatable smhh
lmao
honestly if you're no longer only using if statements, it means you're now a better programmer then someone whos been making a game for like 10 years
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
๐
thanks?
welcome?
huwunter is hereee
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
thanks, replacing requests with aiohttp was perfect
hi i have this issue when i add f before command description its no longer seen as command desc
i mean when i make it f string
show code
i mean this ```py
@commands.command()
async def roll(self, ctx: commands.Context, dice: str):
f"""Rolls a given amount of dice in the form \d\
Example:
```
{ctx.prefix}roll 2d20
```
"""
i want this to be current prefix but when i add f string its no longer seen as desc
top is with f string
i see - docstrings cant really have f strings considering the variables havent been declared - instead you can use {} and .format
inside of a string?
!e py string = "hello {}" print(string.format("Fred"))
@manic wing :white_check_mark: Your eval job has completed with return code 0.
hello Fred
did that and doesnt work
did like this ```py
"""Rolls a given amount of dice in the form \d\
Example:
\`\`\`
{}roll 2d20
\`\`\`
""".format(ctx.prefix)
oh okay
you can keep the {ctx.prefix} syntax
it works with format too
>>> user = Mock()
>>> user.name = "dave"
>>> "hello {user.name}".format(user=user)
'hello dave'
i think i did something wrong
does anyone know a good tutorial for a python economy bot that works with replit?
Tutorials for discord.py are are outdated and are quite useless, you're better off reading the docs and the github examples
Also replit ๐ฌ
too many people say this to me...
And for good reason :p
Replit is unintentional beginner bait
Not to mention it's garbage
Which is as mild as I can put it
There are a bunch of really awesome editors, pycharm, vscode, atom, whatever you want that you can use instead of replit
Vscode is fairly common for new coders
Yep, it's a very good tool for both beginners and experts alike
thats the code ```py
for file in os.listdir("modules"):
if file.endswith(".py"):
bot.load_extension(f"modules.{file}")
@commands.Cog.listener()
async def on_dbl_vote(self, data):
member_id = data["user"]
channel = self.bot.get_channel(882354495466663936)
reward = random.randint(800, 1000)
await channel.send(f"<@{member_id}>, you have earned {reward}$TPET from voting on top.gg! Thank you! (Dev info: {member_id})")
await ecomoney.update_one({"id": member_id}, {"$inc": {"bank": + reward}})
won't add the reward to the database
every file in this folder is a cog
is it correct? py guilds = await cluster.find() for x in guilds: channel = x["channel"] c = client.get_channel(channel) await c.send("Test")
how do I make my bot give a certain role?
anyone here with a bot on discordbotlist? If yes, how do I get the webhook to work?
wdym
well, I can't help
idk
why does 1 application have multiple bots?
what?
i didn't understand it, because when you invite the bot, it uses the application ID, but the application can have multiple bots. and each bot has its own token. does this mean that actually you can invite a whole bunch of bots in one go? so its like a giant bundle of bots?
but none of the bots seem to use that
oops nvm its a one to one thing
One application can have one bot, one oauth2, etc
whats oauth2
how do I add slash commands to my bot
https://datatracker.ietf.org/doc/html/rfc6749 Heres the RFC for it, in a nutshell it's an authorisation system
The OAuth 2.0 Authorization Framework (RFC )
I do recommend reading the RFC, good knowledge to know
is it the thing websites can use to let people log in with their discord account
Yes
yes
actually working with it right now ๐
i think its just message starts with the slash? idk though
nvm
looks different
Either need a fork or implement it yourself within discord.py
on_interaction does pick up those so it's worth keeping in mind
Pick one of the existing ones
Or go with a different library
Pycord, disnake, nextcord, hikari are the ones i've heard of
ok
There is still no recovery of discord.py?
Crazy how one wrapper archived and now we got the warring states
why did it ever archive though
Maintainer wasn't happy
its fine i googled it
^
oh nice
@slash.slash(description="test")
async def hi(ctx: SlashContext):
await ctx.send("yooo")
hey, im trying to make a slash command but it never actually responds. it just says interaction failed every time
It doesn't get registered at time most likely
so how can i fix it?
What library do you use?
discord-py-slash-command
does pycord have it with it?
I think it does
oh cool
But personally I can't help with it
how do i take off default HELP command on my bot?
Afaik most of forks have the test_guilds param in bot constructor, use it or its alternative depending on lib
Set the help_command to None in bot constructor
bot constructor is where?
bot = commands.Bot(..., help_command=None)```
bot = commands.Bot(command_prefix=">" help_command=None)
like this?
i forgot the comma
you should subclass your help command, not make a custom one
oh, is that easier or?
He just wants to get rid of it ig
9/10 to make a "better" one
easier to make, easier to read, and just better for the user
!help <command/cog/group/None
In that case check this out
#discord-bots message
@scarlet aurora
i prefer just removing it and then remaking the help command
hi i wanted to create event that does stuff on guild join but in a cog how can i make it since this doesnt work ```py
@commands.event
async def on_guild_join():
pass
it's also dynamic, so you don't have to make a new section in your help command that says how to use the command, it's automatically added
@commands.Cog.listener()
Use this decorator instead ^
Isn't it commands.Cog.listener()?

Oops yeah
Yeah got it confused with bot.listen
!d discord.ext.commands.Cog.listener you can find examples of usage here
classmethod listener(name=...)```
A decorator that marks a function as a listener.
This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
Man do I hate how discord.py does event's/listeners
ty

don't like it much either, but i can't really think of a better way haha
There is take a look at these examples for my wrapper https://github.com/an-dyy/Rin/tree/master/examples
Some libs just have enums containing events
๐ค interesting
Also means I can wait for events without client on-demand
hey also one small question how can i get joined guild id from on_guild_join listener?
member.guild.id
@bot.command()
async def help(ctx):
embed = discord.Embed(
title=f"",
description=f"",
colour=0x3D9AF2)
await ctx.send(embed=embed)``` why wont this work?
Access the id attribute of the guild from on_guild_join
As this event provides the discord.Guild object for you
Pretty sure you either need title or description
Well you are overwriting the builtin help command, not good
ik i have it
and yeah there's already a help command built in
you can customize how it looks by subclassing
rather than making your own from scratch
!d nextcord.Guild
class nextcord.Guild```
Represents a Discord guild.
This is referred to as a โserverโ in the official Discord UI.
x == y Checks if two guilds are equal.
x != y Checks if two guilds are not equal.
hash(x) Returns the guildโs hash.
str(x) Returns the guildโs name.
Because discord expects a character at least for both title and description if you GIVE it. You can just omit these kwargs if you do not want either
Otherwise use a zero width character, E.g \u200b
Or ** ***
Love the pfp
Brandons cat โค๏ธ
you mean a member?
get the user/member then object.mention or just f"<@{id}>"
thanks
!d discord.Member.mention | just get_member(id) and it will return a discord.Member instance
property mention: str```
Returns a string that allows you to mention the member.
then no {}
just a webhook embed
Ignoring exception in command prefix:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 168, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\testing\modules\config.py", line 29, in prefix
await cursor.execute("SELECT prefix FROM prefixes WHERE guild_id = ?", (ctx.guild.id))
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
ValueError: parameters are of unsupported type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\bot.py", line 1055, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 933, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\PC\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\ext\commands\core.py", line 177, in wrapped
raise CommandInvokeError(exc) from exc
nextcord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: parameters are of unsupported type
i get this error
guild_id is not INTEGER
so what is it
idk
check your db
i mean in my db it is int
screenshot
sql dbs need precise data

i can send you my command
thats this command ```py
@commands.command()
async def prefix(self, ctx, prefix: str = ""):
if not prefix:
return
async with aiosqlite.connect("data.db") as db:
async with db.cursor() as cursor:
await cursor.execute("SELECT prefix FROM prefixes WHERE guild_id = ?", (ctx.guild.id,))
data = await cursor.fetchone()
print(data)
if data:
await cursor.execute("UPDATE prefixes SET prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id))
else:
await cursor.execute("INSERT INTO prefixes (prefix, guild_id) VALUES (?, ?)", (prefix, ctx.guild.id))
await cursor.execute("SELECT prefix FROM prefixes WHERE guild_id = ?", (ctx.guild.id))
data = await cursor.fetchone()
if data:
await cursor.execute("UPDATE prefixes SET prefix = ? WHERE guild_id = ?", (prefix, ctx.guild.id))
await ctx.reply("Changed prefix from")
else:
return
await db.commit()
you dont need async with db.cursor
well ill just leave it like that since it worked
ye all good
async with aiosqlite.connect(...) as db:
await db.execute("INSERT INTO some_table ...")
await db.commit()
this is straight from the docs
okay but why my code doesnt work ๐ข
any errors?
yes here
real chads would use slash commands instead of this prefixes pain tbh
i wanna use both
k
y doh
most help commands with slash are fucked
true
for a detect and respond code, how would it be
dont await it
okay
i did that but theres another error for this part of the code
is this remotly right
put strings in ""
whats message
no
oh i
show full event code
how can i make a program search a specific string and download the first corresponding google image, or copy the link so it can be embedded into something like a discord embed? most of the web scraping stuff doesnt work on my mac so it's hard to test
il send the first half
am looking for help
wtf
@client.event
async def on_message(message):
if not isinstance(message.channel, discord.channel.DMChannel):
keys = db.keys()
guild_id = str(message.guild.id)
prefix = await get_prefix(message.guild.id)
if message.author == client.user:
return
elif message.author.bot:
return
elif "discord.gg/" in message.content.lower() and get_antiInvites == True and message.author.guild_permissions.administrator == False or "discord.com/invite/" in message.content.lower() and get_antiInvites == True and message.author.guild_permissions.administrator == False:
await message.delete()
ni = discord.Embed(color = 0xe74c3c, description = f":mfailed: {message.author.mention}, no invite links allowed!")
await message.channel.send(embed = ni)
guild_prefix = await get_prefix(message.guild.id)
prefixLength = len(guild_prefix)
if message.content.lower()[0:prefixLength] == guild_prefix:
msg = "-" + message.content[prefixLength:len(message.content)]
await client.process_commands(msg)
Have you learned python yet?
he has arrived!
theres something before the first line
but i tried a few things but got the yellow or red lines
but the code still isn't right
for whos code is this
Why is there ("(lfg)") after the decorator?
should learn oop and python
theres supposed to be something before, to detect the lfg, the def of lfg is above the code
thats what i need help with
@hushed field also if i don't "await" it then it just adds another field to the collection
What
something to detect lfg
What is lfg
it stands for looking for group
need something to detect that and respond with a gif
jus need the detector part
thats not a tuple
!e
a = ("not, a, tuple")
b = ("a", "tuple")
print(a)
print(b)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | not, a, tuple
002 | ('a', 'tuple')
ohhh
you should learn dpy
that's some high level piton
this better?
this even better
ok i know i suck at this
should be a list but yeah
had you tried learning it before doing it, it would look much better
how do i fix defining message, and ctx, ctx was used earlier and worked perfectly fine
guys just spoonfeed tbh
async def on_message stuff comes directly after the decorator
and the if statement's gonna be within that
Yes sir!
since you don't have a context in an event, you wouldn't use it
so replace ctx
with message.channel
because you have a message once defining a function correctly
@fervent shoal
https://vcokltfre.dev/
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
how'd you define message
@bot.event
async def on_message(message: discord.Message):
if lfg in message.content:
await message.channel.send("link")
thank you so much ๐
Spoon feeding at its finest
just use a command and use aliases
don't convert message into an str
oh
I gave them what they wanted
process_commands doesn't take a string
ยฏ\_(ใ)_/ยฏ
so what do i do???
atleast make it a listener๐ญ
process_commands takes just the whole message object
i see, well im using guild custom prefixes
and when i define client
client = commands.Bot(command_prefix = "e", intents = intents, case_insensitive = True)
i can't do get_prefix because it requires a guild id
im not sure how i'm supposed to define it
client = commands.Bot(command_prefix = get_prefix, intents = intents, case_insensitive = True)
like that?
why is this happening, never happened before
yeah, and get_prefix is a function returning the correct prefix for that specified guild_id
I gave them exactly what they wanted
ยฏ_(ใ)_/ยฏ
yes
fine๐
def get_prefix(ctx):
if ctx.guild.id == 6874894524:
return "!"
I think it's like that, I'm not sure how get_prefix gets the context
well
why is it doing this when i run it without debugging
it doesn't work like that?
oh shi
wdym
yeah you don't use that because...?
Can someone explain something to me? If you do:
bot = commands.Bot(prefix=get_prefix)
get_prefix has access to bot and discord.Message
But you're not calling the function get_prefix
so you just want me to do
async def get_prefix(ctx)
So how does it even get called?
Imma look at some docs
def get_prefix(client, message): ##first we define get_prefix
so client replaced with bot
okay
and the guild's id you get by message.guild.id
no, you don't call it yourself
alright
you just pass it to your bot's prefix kwarg
well how you change and store your prefixes is your own choice
https://stackoverflow.com/questions/64513680/discord-py-prefix-command
I was just reading this
this tells you to use json, but just use a database
alright thanks
it can be async right
thanks
Traceback (most recent call last):
File "C:\Users\W\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\E\riot bot 5, no way this works.py", line 70, in on_message
if lfg in message.content:
TypeError: 'in <string>' requires string as left operand, not tuple
so the string was wrong
and my monke brain is not working
the source code itself calls the function, because it's just an overwritten function
if you'd name it something else, it wouldn't even work
Ah
discord/ext/commands/bot.py line 904
async def get_context(self, message: Message, *, cls: Type[CXT] = Context) -> CXT:```
discord/ext/commands/bot.py line 866
async def get_prefix(self, message: Message) -> Union[List[str], str]:```
it's there 
if lfg in message.content:
TypeError: 'in <string>' requires string as left operand, not tuple
so if i understand this correctly, the in message.content is messed yup
understandable
you can't just
if every chips in can of pringles
go through the list and check every string in it
basically, but no, but almost
lfg=("lf1m", "lf2m", "lf3m", "lf4m", "lf5m", "lf1", "lf2", "lf3", "lf4", "lf5", "lfg", "lf")
this one?
yeah, go through it with a for loop

because youre doing if tuple in string
for i in lfg:
if i in message.content:
#something's in it, stop and do something
๐ช๐ถ
...
just check if the author is the bot
yea
the bot is sending it
that's why
cool
how do i fix >.<
return the function
its in a for loop so for each element it will send that
return
!e
for a in range(1, 10):
print(a)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
006 | 6
007 | 7
008 | 8
009 | 9
okimii
?
that was a really bad example
๐
return what
be like me
what am i returning
true true
that was a wise example
just do return await ...
sorry๐
!resources Riot
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
delete the first one
no problem, only me is me, and I'm more than enough bs to this world 
the first await?
yes
to match the if statement?
and remove (message) there
no, to be 1 indent infront of it
can i restrict what channel it cannot go in
ofcourse...?
correction, how do i restrict it
check for example for the message's channel's id
if channel(channel),

you are speak big words wise one
if message.category.id == *some big numbers*:
return
get category's id by enabling developer mode on discord, right clicking the category in discord and copying id
and then replace some big numbers with that
just return
if you return at the start, the function's not gonna continue
P Y T H O N T E A C H E R
like so?
uh I think it would be better after the first if but before the return await
on the same level as the return await
so what do i change
or maybe even just after the for line
and after defining the function, check
if message.author.bot: return
``` 
I got command that replyโs message.content but I want it to reply after the command and not include the command itself
so im all set
still works the same
prolly
are you using commands?
because like
replies message.content
show us your code
You could use sets to reduce the time complexity on this
a = set(list_of_stuff)
b = set(message.content)
if b.intersection(a):
...
@cold sonnet there is no message.category.id
it doesnt exist according to this code
do i have to import something
async def test(ctx, *, reason=None):
await ctx.author.send(ctx.message.content)
await ctx.author.send(reason)
Ok
why is it named reason
@client.command()
async def shop(ctx):
em=discord.Embed(title=f"Shop",description = f"the shop :/")
for item in mainshop:
name = item["name"]
price = item["price"]
description = item["description"]
icon = item["icon"]
em.add_field(name=f"{name} | {icon}", value = f"{price} Coins \n{description}")
em.set_footer(icon_url = ctx.author.avatar_url, text = f"๐ธ | Requested by {ctx.author.name}")
await ctx.reply(embed=em)
it keeps on saying invalid syntax
Idk lmao it was for testing something else
What line?
3rd
Ok
nah nothing's wrong there
but there's absolutely no need for f-strings
ok iguess ill leavit it
lacking pep8
Will this fix it?
I donโt think it will Lmao
Ok Iโll try
await ctx.author.send(reason if reason else "Send something or I'll kick your ass")
reason or โsome random reason" also works instead of reason if reason else
if you don't pass anything when invoking the command, it won't work
Ok
this would work in any situation
Ok
because it checks if reason's None
none of these are working now
you copied all of that 
me?
@cold sonnet will [reason] work for a command like test.com/@[reason]
i am unable to see where
@bot.command(name="ping")
async def ping(ctx: commands.Context):
await ctx.send(f"Pong! {round(bot.latency * 1000)}ms")
@bot.command(name="ban")
@commands.has_permissions(manage_roles=True)
async def ban(ctx: Context, member: Member):
await member.ban()
embed1 = discord.Embed(title=f"{member}", description="insert description here")
await ctx.send(embed=embed1)
@bot.command(name="kick")
@commands.has_permissions(manage_roles=True)
async def kick(ctx: Context, member: Member):
await member.kick()
await ctx.send(f"{member} has been kicked")
@bot.command(name="mute")
@commands.has_permissions(manage_roles=True)
async def add_roles(ctx: Context, member: Member):
await member.add_roles(discord.Object(id=938658120715104306))
await ctx.send(f"{member} has been muted")
@bot.command(name="unmute")
@commands.has_permissions(manage_roles=True)
async def remove_roles(ctx: Context, member: Member):
await member.remove_roles(discord.Object(id=938658120715104306))
await ctx.send(f"{member} has been unmuted")
no not in these
why does the code look thiny never work
of your on_message
LOL
idk how this helps the commands on top 
how do i do this right
but there's a much better way without process_commands
and an easier one
replace @bot.event above the on_message line with @bot.listen()
Why do u have so many arguments
so the decorator won't work the same
so now you have something like
@bot.listen()
async def on_message(message):
...
waiting
parantheses
yes
to @bot.listen()
am i set
yes
