#discord-bots
1 messages · Page 724 of 1
just use their animal endpoint instead of 2 different endpoints
the second website gives a 404 response
https://some-random-api.ml/endpoints yeah there aint any red panda facts
make your own medals till 10
yea but you can still use it for top 3 people , ive seen bots doing it
^^
these type are simple and easy to make
there actually is in the docs though
so something like that only
Top 10 get medals? Sounds like pity medals kek
yeah ig they want uniformity in the leaderboard
or u could give them something else instead of metals
medals*
theres this (as infermwafnwa) said https://some-random-api.ml/animal/red_panda it has facts and images both so yeeaa it can be used
amari bot
vouch
indeed
i am a helper in that api's support server hehe
You mean aiosqlite?
aiosqlite is the wrapper , sqlite3 is th database
you should shift to aiosqlite , since it fits with the async syntax and is non blocking
you wont have to learn anything new , just adding some awaits will do the work
nope, shouldn't
.
You just need to add some awaits
it will make your bot non-blocking
so if someone uses a command which uses sqlite3 , you bot doesnt freeze
You want to make your code as async as possible
Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!
okimii tha saviour
That's is a very large embed
you should explain what is sync and async is
well well well , if they make discord bots they might be already familiar to async
!pypi Db
i mean they should know the difference
#bot-commands
yeah ofcourse
ok
Does anyone know how to replicate yagpdb's controlled randomizer?
should show them how it blocks with time.sleep thats how i learned what blocking was
pip install aiosqlite if that's what you mean
I tried to replicate it, but my solution won't work.
It's just a wrapper for the sqlite3 db
sql = db language
sqlite = db
aiosqlite = async instance of the sqlite db
basically , using await before everything you did with sqlite3
sqlite3 ```py
connecting
sqlite3.connect(....
executing cursor/db
cursor/db.execute(....
**aiosqlite** ```py
# connection
await aiosqlite.connect(....
# executing
await cursor/db.execute(.....
``` same goes for `commit` , `fetchone` and `fetchmany` too
the queries remain name
*same
More like aiosqlite is an async driver for sqlite
@hidden hazel remember coros need await
def function():
print("sync function")
#calling the function
function()
if it were a coro it would be
async def asyncfunction():
print("async function")
#calling the function
await asyncfunction()
shhhhhhhhhhhhhhhhhhhhhh
you can use multiple dbs , or multiple tables in the same db
theres dbs that use servers like postgresql
You should use a single database, and a redis cache
whats redis cache?
That's what a lot of big corps use, and for good reason
!pypi redis
A really good tool for caching
ill assume for not putting too much load on the database , right?
im gonna slack on jarvide tomorrow and learn sql dont tell caeden

Yep, good for taking some load off your database
Also slows down latency if your accessing through memory via redis
you know how he is
indeed the announcement yesterday lmao
smh i got bullied by snowy for like 7 spacing errors 😔
well when u run it , you actually get to know if thats an error or its normal
Spacing errors?
Did you make indentation errors kek?
no
spacing errors in params smh
i was in a hurry 😔
🤔 how can spacing in params get you an error? example pls
nothing i just wasnt following pep8 smh
😔
use black ez
param(self, ctx,*,something)
he bullied me for something like this
😔
lmao
Oh yea that is really triggering
shut up
no its not
he even made me read pep8 from top to bottom😔
I wouldn't blame him ¯_(ツ)_/¯
I WAS IN A HURRY AND IT WAS 3AM😔
the pain
and i already knew it😔
im going to sleep gn guys
gunnite
gannnute
docs.......................
🕵️♂️🏃
db1 = # connect to db from which to transfer data
db2 = # connect to db in which data is to be transferred
# get all data from db1
db1.execute("SELECT * FROM tablename")
data_tuple = db.fetchall()``` and then you can write all the data from db1 to db2 using a loop
or wait there's an easier way
How to copy a table to another SQLite database?
PEP-8
That's triggered
Follow pep8 please
working on a ping command how do I get it to quote the before edit
@bot.command()
async def ping(ctx: commands.Context):
message = await ctx.send(f"before:`{round(bot.latency * 1000)}ms`")
await asyncio.sleep(2)
await message.edit(content=(f"after:`{round(bot.latency * 1000)}ms`"))
Can anyone tell me why my code isnt working
im trying to make a welcome message get sent to dms but it wont work and the error says fun object has no attribute 'member'
@commands.Cog.listener()
async def on_member_join(self, member):
print("Welcome message sent in DMs.")
languages = random.choice(langs)
embed = discord.Embed(
description="WELCOMEEEEE"
)
embed.set_author(name=f"{languages} {self.member.name}!", icon_url=self.member.avatar_url)
await member.send(embed=embed)```
can someone help?
Ill try
ok
self represents the instance of that class called 'fun'
What do you expect as self.member.name? if you want the bot's instance you probably may have passed it as self.bot so use self.bot.name. Or if you want the joined member's name in that event use member.name
okii
what's the format?
ohhh
@bot. command ()
@is_registered
40 y async def balance (ctx,commands, Context member: Discord.Member = None):
thanksss
I think
You don't receive ctx in an on_message event, you receive a message object. So the id variable would probably be message.author.id and you can access the message's channel by message.channel
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
Anything your defining like member goes in that ctx () i call it the define box
Ok thank you
Add a space infront of the await until it doesnt have a red line under it i see your using replit
yepp
this is the pic
if I put it in 47, the user_account= will be invalid syntax
and the red line didnt get rid of
Send a screenshot of the entire command
okiii
Your indentation is wrong, probably
@is_registered
async def balance(ctx,command,Context, member: discord.Member = None):
if not member:
member = ctx.message.author
user_account = await economy.get_user(member.id)
embed = discord.Embed
colour=discord.Color.from_rgb(244, 182, 89)
embed.add_field(name=f"{member.display_name}'s balance", value=f"""Bank: **{user_account.bank}**
Wallet: **{user_account.wallet}**
Items: **{user_account.items}**""")
embed.set_footer(text=f"Invoked by {ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
await ctx.send(embed=embed)```
so this is the command
Either send a screenshot or use
ohhh
this is the code
Either send a screenshot or use https://paste.pythondiscord.com
Okay
Your indentation is definitely wrong
Every line in the screenshot after the if block should have the same amount of spaces as the if block
how?
That's how Python indentation works
so i will indent one space on each?
If that's your indentation, yes
oh
I see you have word warping, I hate that thing. You can disable it in the settings
word warping?
@brazen raft
!local-image
a minute
!local-file
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
how do i send a message to another channel
if i like said "!send hello" then it would send to another channel
how do i do that
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
get the channel and use .send()
do i have to put the channel id in the ()?
yessir
do i put the .send() after the get_channel ?
or do i put it on another line
get_channel
how to make the bot send an embed with dropdown menu? and if user click one of the menu the bot edit the embed (edit not send another message)
- does that module exist
- if yes did u pip install it
idk i don't use replit but it's probably the same
pip install DiscordEconomy in terminal
thanks
i think u have to do it in shell but i might be wrong
oh nvm yeah u have to do it in terminal
?
what will I put?
pip install DiscordEconomy
uhmm it doesnt work HUHU
shell
i searched up on the discordpy website for status and when I put the code it didnt work. client = discord.Client(activity=discord.Game(name='my game'))
hey, cant read messages, no intent, plz help
Do i need to learn everything in object oriented programming to learn asynchronous programming?
What topics is useful for disnake
you need to enable intets by putting this code into the prefix:
, intents=discord.Intents.all() and also enable all the intents at discord.com/developers/applications
its below the 2Auth
i did
still no work
send pic of the code and the bot page
:(
I got rate limits
Have to wait 1hour.
sad...
Is there any ways to unlock rate limits?
:(
Anyone ping me to awnser
@client.command()
async def clear(ctx, amount=5):
author_id =ctx.author.id
guild_id = ctx.guild.id
dbc.execute('select * from guilds where guild_id = ?', (guild_id,))
flag = dbc.fetchone()
if flag == None:
await ctx.send('Guild not registered. Please use `>guild`.')
else:
dbc.execute('select modrole_id from guilds where guild_id = ?', (guild_id,))
modrole_id = dbc.fetchone()
if modrole_id == None:
await ctx.send('No `modrole` defines.')
else:
user = client.get_user(author_id)
guild = client.get_guild(guild_id)
modrole = guild.get_role(modrole_id)
if modrole in user.roles: # user has now attribute role error
await ctx.channel.purge(limit=amount)
else:
await ctx.send('Only a `moderator` can do this!')```
any clues?
How do I make a statistics bot?
cuz i mean i was hoping to create a dashboard like carl bot
or any sort of public bot
Yes
But i would assume i would have to do it with flash
sorry flask
In this video, we will make a discord bot dashboard using Python (Flask) in 2021
Code: https://github.com/CodeWithSwastik/Dashboard-Tutorials
If you have any suggestions for future videos/doubts, leave it in the comments below. I might not be able to answer everyone but you can join my discord server for help: https://discord.gg/TXF3hBj
Some ...
Watch this
Is that your best recommended video?
Yes
If you want it quick and easy
https://youtu.be/56Zw8-eaNq8 look at this series if your looking into more in-depth stuff
A LOT of you have been asking for a new bot dashboard series, and here you have it. This will be a series where I will show you how to create a Discord bot web dashboard using Python and React.
In this video, we will be creating a bot with a custom prefix, welcome, and leave messages.
😀SUBSCRIBE for more videos! https://youtube.com/c/ahnafza...
read the docs if you are really into indepth stuff
tutorials are shit
It’s about bot dashboards
flask has docs too
Oh yeah
Thought you meant about discord.py
mhm
can i run fastapi on the same server where my discord bot is running
Like a bot that'll extract data from a website, an example would be an MMA bot that'll give you access to all the latest fights and predictions.
This is against a lot of websites TOS
Public APIs from the websites aren’t though
webscraping 😐
Beautiful soup 🍜
They should sell it at restaurants
Wonder what it tastes like
Web scraping your mouth
😋
Back to topic
yes ♥️
can i run fastapi on same server running discord bot ?
whats the performance cost ?
class discordBot:
@bot.command()
async def whois(ctx, member : discord.Member):
embed = discord.Embed(title = member.name, description = member.mention, color = discord.Color.red())
embed.add_field(name = "ID", value = member.id, inline = True)
embed.add_field(name = "TEST", value = "test", inline = True)
embed.set_thumbnail(url = member.avatar_url)
embed.set_footer(icon_url = ctx.author.avatar_url, text = f"Requested by {ctx.author.name}")
await ctx.send(embed=embed)
if __name__ == "__main__":
discordBot()
``` yo this comes up with the error '```
discord.ext.commands.errors.CommandNotFound: Command "whois" is not found``` anyone know why
Full traceback
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "whois" is not found```
Not full traceback
Put it out of the class
na bro I wanna make it all in the class, works out of the class
thats not how you subclass a Bot
class discordBot(commands.Bot):
def __init_(self):
# stuff
pass
bot = discordBot()
@bot.command()
async def cmd(....
bot.run()```
basically u need to subclass the bot object , not make a class
ah
okay but how do I pass variables through different commands /functions @slate swan
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
I want to make a !buy command. How can I detect what thing the person wants to buy without needing to create multiple commands for each item?
async def buy(ctx, *, item)
what do i put in the * instead?
The * is saying that the item var can be multiple words
Yes
With this ‘v!buy ham-burger 2’ would work
Buying 2 ham burgers
so I just type like this:
@bot.command()
async def buy(ctx, item, amount: food = 10):
await ctx.reply("You bought food")
async def buy(ctx, item, amount: house = 10000):
await ctx.reply("You bought a house!")
in one command
Need help how do i split multiple line into single line?
amount: food = 10 isn’t gonna work
then how is it gonna work?
amount is the variable storing the amount
:int is showing that it has to be an number
can u send an example using like the word weapon?
And = None shows that you don’t need the variable
Ok
And splitlines doesn’t work
okay
ill send an example of how i thought it will work
@bot.command()
async def buy(ctx, weapons, ammount: int = None):
await ctx.reply("You got weapons")
hmm
No
@bot.command()
async def buy(ctx, *, weapons, amnt=None):
amnt = int(amnt)
@kind wind
does it work?
and where do i put the name of the item?
Wdym
Anyone know why this code does not work for me?
async def selectboxTesting(ctx):
await ctx.send(content = 'Select an option! ', components = [Select(
placeholder='Select something',
options= [
SelectOption(label='Option1', value=1),
SelectOption(label='Option2', value=2),
SelectOption(label='Option3', value=3),
SelectOption(label='❌ cancle', value='cancle')
],
custom_id= 'SelectTesting'
)])
interaction = await client.wait_for('select_option', check=lambda inter: inter.custom_id == 'SelectTesting' and inter.user == ctx.author)
await interaction.send('you chose an option')
what’s wrong
I choose something and it writes to me interaction failed
try overwrite
What do you mean?
overwrite just like @bot.command()
ok i will try
K dude if not works srry cuz i use discord_button_plugins only
yo
Yo
class MyBot(commands.Bot):
def __init__(self, command_prefix, self_bot):
commands.Bot.__init__(self, command_prefix=command_prefix, self_bot=self_bot)
self.message1 = "[INFO]: Bot now online"
self.message2 = "Bot still online"
self.add_commands()
async def on_ready(self):
print(self.message1)
def add_commands(self):
@self.command(name="status", pass_context=True)
async def status(ctx, member : discord.Member):
embed = discord.Embed(title = member.name, description = member.mention, color = discord.Color.red())
embed.add_field(name = "ID", value = member.id, inline = True)
embed.add_field(name = "TEST", value = "test", inline = True)
embed.set_thumbnail(url = member.avatar_url)
embed.set_footer(icon_url = ctx.author.avatar_url, text = f"Requested by {ctx.author.name}")
await ctx.send(embed=embed)```
not sure why I get this error, got an idea?
``discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.``
I didn't?
@kindred drum
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'
Dude
Bruh 💀
i know why
member return out with member.name
so you dont need member.name
you can do member
Discord.member is a member object
It’s nonetype because it is equals to None
And hasn’t been passed
I still don't get where I pass it
still nope
Is getting bug?
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
try member : discord.Member=None yet?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'
wait
i did that and now its working
i’ll fix your code real quick
lel
member = commands.fetch_user(member.id)
member.mention
@kindred drum
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: module 'discord.ext.commands' has no attribute 'fetch_user'
@eager trail
cogs? I aint using them
AttributeError: 'Embed' object has no attribute 'set'
any help with this error?
Embed.set_x where x can be footer , author , thumbnail and image
tried it...didnt work
and set_field_at
!d disnake.Embed.set_field_at
set_field_at(index, name, value, *, inline=True)```
Modifies a field to the embed object.
The index must point to a valid pre-existing field.
This function returns the class instance to allow for fluent-style chaining.
Was just listing some examples , they simply did Embed.set
yes but set_field_at is another example
you listed examples so i gave you another example
Gg
show code
if message.content=='bruh':
await message.channel.send('ok')```
the code that's causing the error
that's not it
shall i send my whole bot code?
await coro(*args, **kwargs)
File "c:\Users\hp\Pictures\Python\turd.py", line 60, in on_message
if message.context=='bruh':
AttributeError: 'Message' object has no attribute 'context'
i get this...is it line 60?
.
its showing like that in terminal coz i had changed context to content
@client.event()
TypeError: event() missing 1 required positional argument: 'coro'
Press any key to continue . . .
There should be no brackets
mb
Also could you please show where you define client?
it worked... @slate swan thanks for the help mate
If you define it like client = commands.Client it is the wrong way
i didnt do it that way
client=commmands.bot
Ok this is good
the b in bot is capital btw
ik dude it was just to clarify..
what wrapper for lavalink should i use for my music bot ? lavalink.py or wavelink.py ? and why ?
youtube_dl ? against youtube Tos ครับ ?
100 + servers
13 k users
now using wavelink no bug. Just want to ask for suggestion. anyone ?
?
!warn 668433997189087232 Remain on topic, and only speak in English, as per our #rules
:incoming_envelope: :ok_hand: applied warning to @eager trail.
@oblique adder we won’t help with your project here, as YT;DL is against discord TOS and violates our 5th rule
My fault not him
did u even read my question ?
he is using wavlink
i even said it is against tos myself
I’m not sure what your question is. You seemed to ask whether YTDL was against TOS or not, and then for help with lava link
I am asking what lavalink wrapper I should use. He suggested I use ffmpeg but I said it was against youtube tos.
your welcome.
I’m looking at lava link now, and it seems to also stream off YouTube, which is still against their TOS
If your music bot just meant to grab music from YouTube?
if member == None:
await ctx.send('`Member` is missing!')
return
this doesn't work
I mean if they just stream off youtube doesn't that mean the creator get something ? compare to using youtube_dl which straight up download them
this is for my ban command
more detail
if a admin tries to use the ban command without the user argument, it will send a message saying Member was missing
No it isn’t allowed by YouTube tos
any error ?
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Ignoring exception in command unban:
Traceback (most recent call last):
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 706, in _parse_arguments
kwargs[name] = await self.transform(ctx, param)
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
well the error is quite self-explaining
in the command set member=None
you didnt mention a member while running the command
you didnt assign member a value so it say it is missing
that's the point
async def ban(ctx,member=None):
now member is set default as none even if u dont write member it will still be none and not empty
i was seeing if it would send a message if the member argument was missing
what are you trying to do if the member is not mentioned? send a message to mention oe or something?
alright thanks
it worked, thanks again 😄
cool ! , you would be using on_command_error event to handle the error sent as MissingRequiredArgument , hard coding by setting member to None is a really bad way to handle error
wc
alright i'll try that later on, thanks!
Ignoring exception in command unban:
Traceback (most recent call last):
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\bot\recode\main.py", line 88, in unban
member_name, member_discriminator = member.split("#")
AttributeError: 'NoneType' object has no attribute 'split'
lucas?
?
the unban/ban method is from lucas' tutorials
you can just py async def ban(ctx , member : discord.Member):
and use await member.ban() to ban the member.
show code
i don't know, i didn't get it off youtube nor made the code
oh , is that from someone else?
yeah
i don't know if it's made off of lucas or off them
well then , could you show the code?
@bot.command()
async def unban(ctx, *, member = None):
if not ctx.author.guild_permissions.administrator:
await ctx.send("You're missing the `Administrator` permission in order to continue this operation!")
return
if member == None:
emb = discord.Embed(
color=0x3ad8fc,
title='**Argument Error**',
description=f"`Member` argument was missing!"
)
await ctx.send(embed=emb)
banned_users = await ctx.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await ctx.guild.unban(user)
embed = discord.Embed(
color=0x3ad8fc,
title=f'**Unbanned User!**',
description=f"{ctx.author} has unbanned {user}!"
)
await ctx.send(embed=embed)
return
for ban_entry in banned_users:
user = ban_entry.banned_users
if (user.name, user.discriminator) == (member_name, member_discriminator):
...```
bet it looks like this
hm , its from lucas
read the message in the screenshot , it has fix
Traceback (most recent call last):
File "C:\Users\mal\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\bot\recode\main.py", line 86, in unban
id = member.id
AttributeError: 'str' object has no attribute 'id'
The parameter you get is not a member object
You have to use typehint when you declare a command and check if the parameter you retrieve is an instance of the object you want
@bot.event
async def on_member_join(member)
channel = bot.get_channel(925523794666352640)
await channel.send(f"{member} Join the server!")```
Does not work for me, anyone know what the solution is?
@bot.event()
How to fix this man
I know, my mistake in writing
And it does not work yet
should work now , if you have memebr intents
!pypi utils
what utils?
i mean if you mean discord.ultils , import it from discord
If it is not then you should try to convert it, if it can't be converted then probably it is not an object
I have, still not working.
For my friends it works, for me it does not.
can you show your intents
ok
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True```
did you pass it to your bot object?
if not , do it
bot = commands.Bot(..... , intents = intents)```
Oh okay
@client_main.event
async def on_message(message):
if message.author == client_main.user:
return
if message.content.lower() == "upgrade" and "th":
await message.channel.send('As a reminder make sure youre fully maxed defence, troops, heroes, and spells before you upgrade. **We do not allow rushing, if you rush we will ban you unless if you get direct permission from Vondy.** Rushing is stupid 98% of the time.')
Now everything is working well, thank you sir!
no worries
hey how do i make it where, if someone say 2 keywords in full, it'll reply with the message?
if keyword1 in message.content and keyword2 in message.content:```
yo why does this listener not react when a user joins ``` @commands.Cog.listener()# Checking the user when they join to see if they have been verified
async def on_member_join(member):
print("[INFO]:{member} has joined")
!or
When checking if something is equal to one thing or another, you might think that this is possible:
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
It's the same concept for and
member intents , and self as the first param in cogs
thnx
Anyone know how to make docs using **sphinx **module ?
in the commands.Cog.listener() para?
What does this have to do with a discord bot?
any help how to fix this?
Because it's related to my bot
That seems like code for self bot
Nvm I fixed it
Hi
I have a clear command working, but I want it to send a certain message when the amount argument is not a number. I've played with if amount != int: but it keeps giving me errors. So I'm using @clear.error but when the isinstance == True, I don't get a response.
How do I get @clear.error to have the bot respond in the channel?
@client.command()
@commands.has_permissions(manage_messages=True)
async def clear(ctx, amount: int=10000000):
if amount == 10000000:
await ctx.send(embed=discord.Embed(title="Error", description=":x: You didn't specify how many messages you'd like me to delete.", color=red))
return
if amount < 1:
await ctx.send(embed=discord.Embed(title="Error", description=":x: I can't delete less than 1 message.", color=red))
return
if amount > 0:
await ctx.channel.purge(limit=amount+1)
await ctx.send(embed=discord.Embed(title="Success!", description=f" Successfully deleted `{amount}` messages.", color=green))
await asyncio.sleep(1)
await ctx.channel.purge(limit=1)
@clear.error
async def clear_error(error, ctx):
if isinstance(error, commands.BadArgument) == True:
await ctx.send("worked2")
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
yes, ctx is first
async def clear_error(ctx, error)
also, I'm kinda late so I'll ping @trail raven
It worked, thanks!
import discord, logging, json, requests
from discord.ext import commands
with open("config.json") as f:
config = json.load(f)
client = commands.Bot(command_prefix=config['Prefix'])
@client.event
async def on_ready():
print(f"{client.user.name}en er klar til brug")
message = {
"content" : (f"Så {client.user.name} klar igen")}
requests.post(config['Webhookurl'], data=message)
@client.command()
@commands.has_permissions(administrator=True)
async def removediscord(ctx, discord):
mycursor = mydb.cursor()
sql = f"DELETE FROM main_database WHERE discord_id = '{discord}'"
mycursor.execute(mysql)
mydb.commit()
user = await client.fetch_user(int(discord))
embed = discord.Embed(
title = f"User: {user} \nDiscord ID: {discord}\n\nStatus: Added user to database ✔️",
color = 0x7CFC00
)
await ctx.send(embed = embed)
@client.command()
async def removediscord(ctx, error):
if isinstance(error, commands.BadArgument) == True:
await ctx.send("worked")
if __name__ == '__main__':
client.run(config['Token'])
in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: discord is a required argument that is missing.
Need help
hi i need help
how i can make an forever loop in d.py without stopping the bot
ping me if you are going to tell me something
import discord, logging, json, requests
from discord.ext import commands
with open("config.json") as f:
config = json.load(f)
client = commands.Bot(command_prefix=config['Prefix'])
@client.event
async def on_ready():
print(f"{client.user.name}en er klar til brug")
message = {
"content" : (f"Så {client.user.name} klar igen")}
requests.post(config['Webhookurl'], data=message)
if __name__ == '__main__':
client.run(config['Token'])
@supple summit
In client event you can just replace with anything
why i need logging and json
i need more better example
because i can't understand the previous one
message = {
"content" : (f"message) ")}
requests.post(config['Webhookurl'], data=message)
@tacit horizon
Can u send your code then
:O
Why [0]
i just want to make a loop for some stuff
like checking database every 10 seconds
for cooldown thing
while True:
Print("hello world")
without stopping the bot or smth
That does not stop the bot
ok
But the while True:
Will keep looping
is it better to store user_id as int or string or there is no differance?
As in database?
yes
Could u help me create a database?
sure
in Dm? or
i think dm is vetter
try printing the value first
like this
print(response[0])
keyerror implies that message key doesn't exist
import discord, logging, json, requests
from discord.ext import commands
with open("config.json") as f:
config = json.load(f)
client = commands.Bot(command_prefix=config['Prefix'])
@client.event
async def on_ready():
print(f"{client.user.name}en er klar til brug")
message = {
"content" : (f"Så {client.user.name} klar igen")}
requests.post(config['Webhookurl'], data=message)
@client.command()
@commands.has_permissions(administrator=True)
async def removediscord(ctx, discord):
mycursor = mydb.cursor()
sql = f"DELETE FROM main_database WHERE discord_id = '{discord}'"
mycursor.execute(mysql)
mydb.commit()
user = await client.fetch_user(int(discord))
embed = discord.Embed(
title = f"User: {user} \nDiscord ID: {discord}\n\nStatus: Added user to database ✔️",
color = 0x7CFC00
)
await ctx.send(embed = embed)
@client.command()
async def removediscord(ctx, error):
if isinstance(error, commands.BadArgument) == True:
await ctx.send("worked")
if __name__ == '__main__':
client.run(config['Token'])
wait the bot keep sending "not found" may be the api rip
can be hit with sqlinjection
fix your code
also
did you mean
@client.error
async def removediscord(ctx, error):
if isinstance(error, commands.BadArgument) == True:
await ctx.send("worked")
lol
also you don’t need a == True 💀
if you just do a if isinstance that’s enough
and it should be is True if you want to add it but idk why you do that 
Does this log, in a db? If yes, I’d like some to help me make a db, & how does it recall the info, from the db to a discord channel? 🤔
can you elaborate?
I'm going to make a blacklist system for my bot. Could I achieve this by creating a decorator that checks a database for the user's id and if it finds it returns the function?
yes,
you can also use the on_message event, check if the author is in the blacklist, if yes return
if message.author.id in blacklist:
return
I'm just going to use it to prevent use of the bots commands
Can I have a sample of what the decorator would look like?
I've never made one
i need info
A list of usernames etc. Basic for now, pls
How does the blacklist work?
I think it explained it pretty well
Ok, what bot commands you going to prevent?
Most of them
Thats why I'm creating a decorator
Ok 🤔
Oh yeah, one more thing. With an Sqlite3 db, should I be creating new files or new tables for my different purposes?
Oh ok ty
Different tables
The only extra databases you should have are backups. You don’t need to have more than 1 main database to write and read to.
Alright
Hi, could there be a reason why I might be getting coroutine object has no attribute 'start'
When I try to run a loop?
It's a discord.ext loop btw
Nvm I realised my mistake
hi i am making a moderator bot and i was ran into an error
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
but it looks like i cant send it
Read the embed the bot sent
ok i fix it ty
Decorators
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
• Corey Schafer's video on decorators
• Real python article
Looking at this doc, is the inner functioned needed and what is its purpose?
Could someone provide a better example?
the slow function in that example is equivalent to slow = timer(slow)
timer(func) returns a callable, the inner function
How do you check if a embed or a string was returned from a function?
How do I make my bot send a message to the users dms once they get a certain role from the server?
@commands.command()
async def gebet(self, *, ctx):
url = "https://dailyprayer.abdulrcs.repl.co/api/berlin"
response = requests.get(url)
data = response.json()
city = (data['city'])
date = (data['date'])
for prayer in data["today"]:
await ctx.send(city, date, prayer + ": " + data["today"][prayer])
# If you want to request for tomorrow prayer's time:
# for prayer in data["tomorrow"]:
# print(prayer + ": " + data["tomorrow"][prayer])```
You can use isinstance with the return of the function
my brain is hurting trying to fix this
i think the await ctx.send is wrong
like the things that come after it
Thanks! What would I put for the 2nd argument to check if its an embed?
discord.Embed
When you call gebet, don't put in self as the first argument
am i allowed to ask questions about slash commands here
i uh did some changes and
@commands.command()
async def gebet(self, ctx):
url = "https://dailyprayer.abdulrcs.repl.co/api/berlin"
response = requests.get(url)
data = response.json()
city = (data['city'])
date = (data['date'])
for prayer in data["today"]:
em = discord.Embed(
title=f'Gebetszeiten Berlin {date}'
description=f'city, date, prayer + ": " + data["today"][prayer]'
)
await ctx.send(embed=em)``` now the description doesnt work
Sweet thanks, working now. I forgot the discord part 😛 Been a few months since I worked on this bot lol Thanks!
what is the output?
Singapore 17 January 2021 Fajr: 05:52 Sunrise: 07:14 Dhuhr: 13:17 Asr: 16:40 Maghrib: 19:17 Isha'a: 20:31
i did a code before but it didnt show the city and the date
it only showed the times
How many embeds are you trying to send?
And also, you're forgetting the curly brackets in the description line
cool, np
got a bit of an issue, dpy how to check if an arg is either a discord channel mention (get channel) or just a normal string? (do something else)
is it possible to check if the member running a command has (perm) or (perm and perm)?
like: py @client.command() @commands.has_permissions(moderate_members=True or manage_messages=True and manage_members=True)?
could do a custom check. .
how do i do that?
Use isinstance function to check that
When designing a bot that uses internal resources, is there a way to avoid relative-to-repo-root paths or do I just have to suck it?
# this is just an example,
@staticmethod
def is_guild_owner():
async def predicate(ctx):
if ctx.guild.owner_id != ctx.author.id:
return False
return True
return commands.check(predicate)
#to use:
@commands.check(is_guild_owner)
thx!
didnt think of using isinstance ; - ;
Using the != operator would be better here
Its alright
ye, old code before i did a full bot rewrite, dont have a custom check anymore . - .
Hmm
(doesnt excuse me for writing bad code, ig)
Its alright
so, i made a bot on my class server, and i tried to mute my use the timeout feature in my alt accnt for testing, im an admin on my class server, with admin perms, but i can't use the timeout command - py @client.command() @commands.has_permissions(moderate_members=True) async def timeout(ctx, member: discord.Member, time: float = None, *, reason='None'): duration = (time * 60) await member.timeout(duration=duration, reason=reason) try: await member.send(f'''{member.mention} you were put in the timeout chair by **{ctx.author}** for {time} minutes, because: **{reason}**.''') except (discord.HTTPException, discord.errors.HTTPException, discord.ext.commands.errors.CommandInvokeError, commands.CommandInvokeError, commands.CommandError, AttributeError, discord.Forbidden): print(f'Cannot direct message {str(member)}.') await ctx.send(f'''{ctx.author.mention} put {member.mention} in the timeout chair for {time} minutes, because: **{reason}**.''')
so, even with administrator perms, i don't have moderate_members perms?
im using disnake 2.3 btw
it works perfectly fine on my personal server, since there is only me, and my bot there and im the owner
i have a problem while declaring this variable:
async def play(self,ctx,url):
ctx.voice_client.stop()
FFMPEG_OPTIONS = (
"before_options" : "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5",
"options": "-vn"
)```
"before_options" :** "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"**
gives a error and idk why
what is the error?
pyflakes invalid syntax
is pyflakes like discord.py? an api wrapper?
yea
idk, maybe py @client.command() async def play(self,ctx,url): ctx.voice_client.stop() FFMPEG_OPTIONS = ( "before_options" : "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5", "options": "-vn" )
async def foo(self, ctx, *, abc):
What does the * exactly do here?
try doing your client var for the decorator
same shit
it takes all arguments past that as one
anything else you type will be part of that argument (basically doesnt look for spaces to seperate args anymore)
so if i were to enter hello my name is hrlo77 for the last part of the command, the whole string would be the abc
And is that one argument abc here?
yes
got it, thanks
If anyone can help me that would be great
!d discord.ext.commands.check_any
@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if any of the checks passed will pass, i.e. using logical OR.
If all checks fail then [`CheckAnyFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckAnyFailure "discord.ext.commands.CheckAnyFailure") is raised to signal the failure. It inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Note
The `predicate` attribute for this function **is** a coroutine.
New in version 1.3.
though has_permissions should take a list
discord.ext.commands.has_permissions(**perms)
Is making a snipe command against discords tos?
anyone have a solution to this error, i'm trying to create an economy bot with aiosqlite
Here is some of the code
db = await aiosqlite.connect('main.db')
cursor = await db.cursor()
await cursor.execute(f"SELECT * FROM economy WHERE member_id = {member.id}")
result = await cursor.fetchone()
sql = f"UPDATE economy SET wallet = ? WHERE member_id = ?"
val = {result[1] + amount, member.id}
await cursor.execute(sql, val)
await db.commit()
await cursor.close()
await db.close()```
Your function isn't async
ty, funny enough i just found the solution xD
Could someone help me so when i people do !join
it writes peoples id to my folder so they are whitelisted
im making a Discord bot, but if I try to run my code I get this error:
from discord.ext
^
SyntaxError: invalid syntax```
This is my code for the project:
```TOKEN = 'my token'
import discord
from discord.ext
import commands
import youtube_dl
import os
import nacl
client = commands.Bot(command_prefix = "*")
@client.event
async def on_ready():
print('ready')
@client.command()
async def join(ctx):
voiceChannel = discord.utils.get(ctx.guild.voice_channels, name = "music custombot")
await voiceChannel.connect()
@client.command()
async def play(ctx, url: str):
song_there = os.path.isfile("song.mp3")
if song_there:
os.remove('song.mp3')
voice = discord.utils.get(client.voice_clients, guild = ctx.guild)
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
for file in os.listdir("./"):
if file.endswith(".mp3"):
os.rename(file, "song.mp3")
voice.play(discord.FFmpegPCMAudio("song.mp3"))
client.run(TOKEN)```
I don't know where the error comes from, please help!
I would suggest you learn python before jumping in to make a discord bot as its not a beginner project
yeah, but I just wanted a really simple bot that loops an .mp3 file. For my own server^^
I copied most of my code btw
"I just wanted a really simple bot that loops an .mp3 file. For my own server" Blatantly uses ytdl
I copied most of my code
!youtube-dl @tulip mural
I know that is used YouTube know
yes, but it gives me sintax error for some reason
Lets see the error
here is the error
in this message
^
oh, okay!
I know enough to use them in my bot
Just ask your question/send your error
Have you tried using WHERE?
No clue. I only started with sql (3?) days ago
My project will just not work, can someone share me a script of a bot that:
- join a voicechannel when it goes online.
- infinitly loop an .mp3 file.
please help, im looking for it all day 😦
oh...
Looping a youtube video and .mp3 file are very different things
yes, but I want to loop an .mp3 file. not a Youtube video
(my old script was with yt i know)
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
They seriously don't have it aliased?
idk why they dont
It's strange
ikr
makes all the arguments after it kwargs
not quite
then what?
^
oohhhhhhh
if you have one kwarg yes it will eat all text
alr
Alright so I need some help. I'm trying to make a decorator and I have no clue what I'm doing. I wrote the code which (should) be working. Can someone explain to me how to turn this in to a functioning decorator?
async def is_blacklisted(member_id: int): # member_id will be ctx.author.id when I can change this in to a decorator
path = pathlib.Path(__file__).parent.parent.absolute() / "main.db"
connection = await aiosqlite.connect(path)
cursor = await connection.cursor()
await cursor.execute(f"REPLACE INTO blacklisted_members(member_id, reason, data) Values({member_id}, 'random text', 'more text')")
await connection.commit()
await cursor.execute(f'''SELECT member_id FROM blacklisted_members
WHERE member_id={member_id}''')
line = await cursor.fetchone()
if line is None:
await connection.close()
pass
else:
await connection.close()
return
pretty easy to make something a decorator
I've never done it before
def decorator():
async def asyncfunction():
So
def is_blacklisted():
async def blacklisted_check(member_id: int): # member_id will be ctx.author.id when I can change this in to a decorator
path = pathlib.Path(__file__).parent.parent.absolute() / "main.db"
connection = await aiosqlite.connect(path)
cursor = await connection.cursor()
await cursor.execute(f"REPLACE INTO blacklisted_members(member_id, reason, data) Values({member_id}, 'random text', 'more text')")
await connection.commit()
await cursor.execute(f'''SELECT member_id FROM blacklisted_members
WHERE member_id={member_id}''')
line = await cursor.fetchone()
if line is None:
await connection.close()
pass
else:
await connection.close()
return
?
I'm guessing this is wrong
example
def decorator():
def function():
if something in list:
return
@decorator
async def asyncfunction():
i think its right im not sure
I can test it
go for it
Of yeah, how would I get ctx.author.id?
wdym
My goal is to have the decorator check the authors id against the database of blacklisted users
Right now you have to input a member
Is there anyway I can make that default to the author (ctx.author.id)
not sure
cant really say
not really
dont even know sql got bored of it lol
know the basics
lol ikr
im going to make a new bot that uses a db today so i better get to it
not really their just hard to master
lol
wdym annoying?
well we all learn at are on rate and sometimes are answers are always under are noses

lol
ic
Its not working
i think im going to do a atm bot like a atm machine with a db
I'm getting TypeError: is_blacklisted() missing 1 required positional argument: 'member_id'
When I don't put the id
well isnt it needed?
Wait
just add a default value of None
And when I add the id I get TypeError: 'NoneType' object is not callable
No clue. I'll try it
argument naming lmao
@commands.command(name="profile") # Profile Command
async def profile(self, ctx: commands.Context, member: discord.Member = None) -> None:
if not member:
member = ctx.author.id

I'm confused about why I'm getting an exception indicating that my turn_loop method is taking three arguments when it is only supposed to be taking 2:
def done_callback(self, _task: asyncio.Task, ctx, curr_server, settings, count=2):
try:
exc = _task.exception()
if exc:
capture_exception(exc)
message_to_be_sent = f'Barbot had an exception, delayed for {count}: {exc}'
print(message_to_be_sent)
capture_message(message_to_be_sent)
if count:
count *= 2
else:
count = 2
else:
count = 0
curr_server.task = asyncio.create_task(self.turn_loop(curr_server=curr_server, count=count))
curr_server.task.add_done_callback(partial(self.done_callback, ctx=ctx, curr_server=curr_server, settings=settings, count=count))
except asyncio.exceptions.CancelledError:
print('task cancelled :)')
async def turn_loop(self, curr_server, count):
channel_to_be_sent = curr_server.approved_channel
settings = await self.get_server_settings(curr_server)
if count:
await self.error_delay(count)
if curr_server.cypher_mode in self.client.cypher_modes:
settings = await self.cypher_list_updater(curr_server, settings)
if settings:
await self.take_turn(curr_server, settings)
else:
message_to_be_sent = f'**The BarBot cannot be run in {curr_server.cypher_mode} Mode when the Cipher List is empty.**'
await self.message_sender(channel_to_be_sent, message_to_be_sent)
curr_server.task.cancel()
Any ideas? It seems also like it's only happening on my production server and not on my dev build for some reason I'm not really understanding
If I type hint the id to a member then and make it default to None I get TypeError: is_blacklisted() takes 0 positional arguments but 1 was given
This is the current code
def is_blacklisted():
async def blacklisted_check(member_id: disnake.Member = None):
path = pathlib.Path(__file__).parent.parent.absolute() / "main.db"
connection = await aiosqlite.connect(path)
cursor = await connection.cursor()
await cursor.execute(f"REPLACE INTO blacklisted_members(member_id, reason, data) Values({member_id}, 'random text', 'more text')")
await connection.commit()
await cursor.execute(f'''SELECT member_id FROM blacklisted_members
WHERE member_id={member_id}''')
line = await cursor.fetchone()
if line is None:
await connection.close()
pass
else:
await connection.close()
return
Not sure if I'm doing something wrong
This is what I'm putting over the command @is_blacklisted(758119644984115243)
I gtg
Ping me you know what I'm doing wrong
why dont you add a global check
would be alot easier
No clue
I just want to keep my code clean
Oh I misunderstood
you literally just return a bool
!d discord.ext.commands.check ```py
@bot.check
async def blacklisted_check(ctx):
if ctx.author in blacklisted:
return False
return True```
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
this applies to all commands
Is there any way I can make it not apply to certain commands?
There are some that I would like to be only available to blacklisted users
@bot.check
async def blacklisted_check(ctx):
if ctx.command.name in ['a', 'b']:
return True
if ctx.author in blacklisted:
return False
return True```
this - where ['a', 'b'] are the command names you dont want to work
salute
This method is longer
!d discord.on_guild_channel_create
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
!d discord.on_guild_channel_delete
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
Is there a way to bypass cooldowns by having an if statement with a users discord id?
for example
no more cooldown```
How to make a random color for embed?
!d disnake.Colour.random
classmethod random(*, seed=None)```
A factory method that returns a [`Colour`](https://docs.disnake.dev/en/latest/api.html#disnake.Colour "disnake.Colour") with a random hue.
Note
The random algorithm works by choosing a colour with a random hue but with maxed out saturation and value.
New in version 1.6.
thanks
make the prefix "".
and give that user application command perms.
Me either. But seeing how bots I use work that should work too
jesus christ
what
They asked for any message, by setting the prefix to "" it will only work when a valid command is in the message
bruh
The goto is doing an on_message event where you check the ID of the author
You want to make an on_message event, then access the author.id of the message object
!d discord.Message.author
i need help
im trying to make it so leveling doesnt sync across servers,
but for individual servers
!d discord.on_typing
discord.on_typing(channel, user, when)```
Called when someone begins typing a message.
The `channel` parameter can be a [`abc.Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") instance. Which could either be [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel"), [`GroupChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.GroupChannel "discord.GroupChannel"), or [`DMChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.DMChannel "discord.DMChannel").
If the `channel` is a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") then the `user` parameter is a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"), otherwise it is a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
This requires [`Intents.typing`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.typing "discord.Intents.typing") to be enabled.
i need to store the guild id and the user id, but idk how
This @slate swan
heres my code
if message.author.bot == True:
print("message is from bot, ignoring")
else:
with open('level.json', 'r') as f:
level = json.load(f)
if level[str(message.guild.id)] == 1:
with open('messages.json', 'r') as f:
messages = json.load(f)
try:
messages[str(message.author.id)] += 1
except KeyError:
messages[str(message.author.id)] = 1
with open('messages.json', 'w') as f:
json.dump(messages, f, indent=4)
terrible idea to implement a db like that
first error => json isn't a db
then learn how to instead of implementing a bad method
seen this code so many times 
??? What is on_typing here for?
no, surely not
You just need to check if the id of the message author is the same as the user id you want
ever used docs/ is this your first python project? looks like it tbh
can someone just answer my question?
surely not
use an instance of it.. not the class objecy
learn the basics first, then move on from there, you don't want to start this without even knowing the different between and object and a class
you're comparing a class with a user ID, if you know basics, you know that's basically wrong
you have to compare the attributes of 2 objects
worst thing you can do
can someone help me pls
use a database
just ANSWER
get the message author's ID and compare it to the given ID
if it's True, get the channel object, use it's async send method
@heavy folio can you help me
ye
Nice, is this a compiler or interpreted? I'm also making my own compiler but in C++
The user’s unique ID.
take note user and member is different @slate swan
member is in guild, user is a discord user
Ah, same for the compiler bit lol. I've been stuck on writing the Assembly code
this is not that relevant for his on_message event
this guy doesn't know yet that a member basically is a user etc
I also don't think he knows what class object message.author returns
A friend referred me to that guide as well, wasn't much use for me though as I'm aiming for a compiled one
oh
can someone help me
A compiler in python sounds cursed though, thank god I'm writing it in C++
You would just make an argument which you can set as the user id and the guild id
Perhaps a dictionary or something? This would also mean that you don't need global
Or perhaps a bot var
then you're doomed to wait years for questions to be answered
be honest, you just dont wanna help someone that uses json
correct, I don't assist bad implementations
it's for the dev's sake
- he won't come crying when everything is corrupt
- he'll get faster responses since that's the way everyone (should) use(s) it
Not really I've been winging it without any resources
I'm stuck at the parser bit though, I haven't done actual compiling nor evaluation
Hence I'm stuck at the assembly code
Nope
Nope but close
message.author is a User or Member object
You want to access the id property of said object
This returns an integer which you can compare
Yep
dang it, got an io blocking task which blocks the whole bot, how would i run the whole method in another thread and await a result?
You should probably checkout run_in_executor
thx!
actually im not so sure if that is the best. . .
considering im also making threads in the method. . . should be a better way. .
hi
actually nvm, run in executor worked fine. . .
@commands.command()
async def faridmemo(self, ctx, *, member : discord.Member = None):
await ctx.message.delete()
url = "https://cdn.discordapp.com/attachments/794990120791965737/800852985461735424/video0.mov"
download(url)
if not member:
await ctx.send(file=File(fp="video.mp4", filename="Farid_Memo.mp4"))
else:
await ctx.send(f"von {ctx.author.mention} an {member.mention}", file=File(fp="video.mp4", filename="Farid_Memo.mp4"))
os.remove("video.mp4")```
uh
it doesnt send the video
neither does it delete the message of the author
ig this is a unsolveable problem
Which line is the error on?
not sure if a bot can send video's...
also very important note:
you seem to download from url synchronously, this will block other code if not put in an executor
can interaction.followup (discord.py) be responded ephemerally
can i ask how to module.export ||that's discord.js but i want it on discord.py||?
Command handler?
use cogs..
yep
you can use cogs for that. Basically creating a class which has commands from a category
!d discord.ext.commands.Cog
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/master/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CogMeta "discord.ext.commands.CogMeta") are equally valid here.
thanksss
@commands.cooldown(1, 3600, commands.BucketType.user)
@is_registered
async def daily(ctx: commands.Context):
random_amount = random.randint(40, 180)
await economy.add_money(ctx.message.author.id, "wallet", random_amount)
embed = discord.Embed(
colour=discord.Color.from_rgb(47,49,54)
)
embed.add_field(name=f"Daily", value=f"You successfully claimed, random_amount 💎!")
embed.set_footer(text=f"Invoked by {ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
await ctx.reply(embed=embed)```
how can I put the amount in You successfully claimed (random_amount)?
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
^^^
Use a f string , it's similar to ` ` strings in js
f"You got {amount}"
okayyy thanksss
its random
so f"You successfully claimed {random_amount} 💎"
?
@slate swan
Yeah it will work
okay thanksss
property avatar```
Equivalent to [`User.avatar`](https://docs.disnake.dev/en/latest/api.html#disnake.User.avatar "disnake.User.avatar")
hm, does it return an image? and if so bytes?
class discord.Asset```
Represents a CDN asset on Discord.
str(x) Returns the URL of the CDN asset.
len(x) Returns the length of the CDN asset’s URL.
x == y Checks if the asset is equal to another asset.
x != y Checks if the asset is not equal to another asset.
hash(x) Returns the hash of the asset.
if you want the file , you can .read() it
when i do that, it says i need to do await member.avatar.read()
and when i do that, it says it has an invalid start byte
.read() returned a bunch of bytes
but it just gave an error for the bytes
@client_main.event
async def on_message(message):
if message.author == client_main.user:
return
if 'th' in message.content and 'upgrade' in message.content:
await message.channel.send('As a reminder make sure youre fully maxed defence, troops, heroes, and spells before you upgrade. **We do not allow rushing, if you rush we will ban you unless if you get direct permission from Vondy.** Rushing is stupid 98% of the time.')
elif 'townhall' in message.content and 'upgrade' in message.content:
await message.channel.send('As a reminder make sure youre fully maxed defence, troops, heroes, and spells before you upgrade. **We do not allow rushing, if you rush we will ban you unless if you get direct permission from Vondy.** Rushing is stupid 98% of the time.')
elif '!rushed' in message.content or '!upgrade' in message.content:
await message.channel.send(' As a reminder make sure youre fully maxed defence, troops, heroes, and spells before you upgrade. **We do not allow rushing, if you rush we will ban you unless if you get direct permission from Vondy.** Rushing is stupid 98% of the time.')
elif 'should' in message.content and 'upgrade' in message.content:
await message.channel.send(' As a reminder make sure youre fully maxed defence, troops, heroes, and spells before you upgrade. **We do not allow rushing, if you rush we will ban you unless if you get direct permission from Vondy.** Rushing is stupid 98% of the time.')
``` why does this code break every command ?
for example as soon as i comment this out, my !who and my !uptime command works
do py await client_main.process_commands(message)
at the end*
Is it possible to create a check (bot.check) inside a cog/class?
if you dont need to do anything with processing of commands, use Bot.listen which dont need you to process commands
could use Bot.before_invoke for that. because it will be easier with it.
!d discord.ext.commands.Bot.before_invoke
@before_invoke```
A decorator that registers a coroutine as a pre-invoke hook.
A pre-invoke hook is called directly before the command is called. This makes it a useful function to set up database connections or any type of set up required.
This pre-invoke hook takes a sole parameter, a [`Context`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
Note
The [`before_invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.before_invoke "discord.ext.commands.Bot.before_invoke") and [`after_invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.after_invoke "discord.ext.commands.Bot.after_invoke") hooks are only called if all checks and argument parsing procedures pass without error. If any check or argument parsing procedures fail then the hooks are not called.
Context.command
will return thecommands.Command instance of the invoking command
for example,
if ctx.command.name in ("upgrade", "townhall"):
await ctx.send(...)```
Could anyone help me out my embed isn't working am i doing something wrong?
@client.command()
async def cher(ctx):
embed = discord.Embed(
title = 'Cherry Network',
description = "The Cherry Project is a Decentralized Autonomous Organization developing a layer one blockchain network optimized for data operations.",
colour = discord.Colour.orange()
)
embed.add_field(name="Field 1 Title", value="This is the value for field 1. This is NOT an inline field.", inline=False)
await ctx.send(embed=embed)```
how many bots can i make on 1 account ?
Do you want to save the file or something?
from io import BytesIO
from PIL import Image
Image.open(BytesIO(await user.display_avatar.read()))
``` this is what I used to get a byte and open it
i needed to send the icon
but it says that the first byte is invalid
199999
doesn't work
Show code
im on a diff comp rn lol that's why i was offline so long
so i don't have code
are you sure the command is even running
put a print statement
There actually is
okok
yes, 199,999
I have 25 only tho
And this ^
but just letting you know i did py async def bm(ctx, message_id): message = await ctx.fetch_message(message_id) author = await ctx.guild.fetch_member(message.author.id) embed = discord.Embed() image = author.avatar.read() embed = embed.footer(text=f'{image} {author} sent {message.content}')
You cannot send an byte object.....
if you want the icon to appear in the embed below , use the icon_url kwarg
looks like they reduced it, some forum says its 199999
4 yr old tho
its 25 ig
idk how
Mhm maybe they are enforcing teams or something
embed.set_footer(text="text" , icon_url= member.avatar.url)
o
i'll try it when i get back on my device
.bm
why are you fetching member
i prefer fetching instead of get
you dont even need to do get it
message.author will return member when possible
in dms, it wont
that's, the point of bookmarking?