#discord-bots
1 messages · Page 746 of 1
Yeah I dont have much time with schools and everything but i try to find time to read it
You should read it, you will understand python much better 👍
And once you get enough experience and knowledge you will build your discord bot on python :)
Good luck
Ill try now where will i put the variable? on line below the as file: , before or inside that line
You know about files reading?
I mean I can explain that lol
i have to go... ill be here tmr and ask again
Hello good day, I just finished learning the basic of python and I want to create my first goal which is discord bot. Is there any tips you can give me?
Uh wdym? Putting it into embed's description/field or something else?
Footer yes
Like
Posted: <t:1642020999:R>
As far as I know footer doesn't support discord markup
Yeah but then it looks ugly lol
Titles don't support markup as well
You can use a timestamp but sadly it wont be like that
Wait idea
Yeah..
Atleast the timestamp auto updates
You could make your own function that would return the string you need
But it won't autoupdate tho
Already did ```py
def time_now_format() -> str:
return f"<t:{round(datetime.now().timestamp())}:R>"
It returns the timestamp markdown
I mean return something like just 5 minutes ago (but as said it won't autoupdate sadly)
yeah but i think it's kinda pointless to put in the date since it is already on top.
If you do ctx.message.created_at in the timestamp it will auto update
inter.message isn't a thing
Ah
Interaction has something like that as well afaik
I search trough the docs for awhile...
Nvm it's something different
feature request yeet
I'm getting this error :
Command raised an exception: InterfaceError: Error binding parameter 1 - probably unsupported type.
after running this :
cur.execute("INSERT INTO orders(customer, customerid) VALUES (?, ?)", (str(user), (str(cust),)))
Does this look weird?
what might be the issue?
\u thing yes
No the ** ** one xd
I can't remember the \u thingy
This is easier to remember
What database
sqlite3
Well I don't typically use params thingie, not sure how it works
when I run this (missing the other value being inserted) :
cur.execute("INSERT INTO orders(customer) VALUES (?, ?)", (str(user)))
it works, but not when I try inserting another value in there :(
i currently made a very simple discord bot for the first time but i want to add more to it does anyone have any good ideas i could add to it
What's the type of customerid? @weary mirage
erh how can I tell?
cur.execute('''CREATE TABLE IF NOT EXISTS orders (customer, customerid, deliverystat, orderstat)''')
Didn't you create this database?
INSERT INTO orders (customer, customerid) VALUES (?, ?)
``` idk if that space matters
this is all I put when creating the table
You usually specify column type
Probably
What about a user info command inside an embed? :D
Well no error but ```
from quart import Quart, request
from discord.ext.dashboard import Server
app = Quart(name)
app_dashboard = Server(
app,
"secret_key",
webhook_url="",
sleep_time=1
)
@app.route("/")
async def index():
guild_count = await app_dashboard.request("guild_count")
member_count = await app_dashboard.request("member_count", guild_id=776230580941619251)
return
@app.route("/dashboard", methods=["POST"])
async def dashboard():
await app_dashboard.process_request(request)
if name == "main":
app.run(debug=True)
Am trying to make this direct me to the discord login page
How do i do that?
This is more work than a whole Discord bot.
okay I think I might know the problem
quartttt niiiice there is a Discord extension to make your life a lot easier though xD
the discord-ext-dashboard?
quart extension
That exists? Wow
You gotta make IPC though you can't just import random stuff from the bot.
ohh ok which is quart-ext-dashboard?
!pypi Quart-Discord
O
that prob will make my life easier
I figured out the issue, I was setting the value as a string, and I guess that wasn't good 🤷♂️
This is only for oauth though but it's nice since you don't need to bother with that again.
Ok sweet
!pypi discord-ext-ipc
A discord.py extension for inter-process communication.
Combine with this and you got a baby
The website AND Discord bot have to both be hosted on the same host. Else you have to make your own API.
Wdym the same host?
On the same system
ohh ok well theres only showing me pip install nothing else on those 2 ext that you just mentioned?
wdym?
Oh yeah the docs suck
I do have an example i think somewhere in my back pocket..
Interesting extensions
Friend of mine made a good easy example.
This is the IPC aka internal API code
https://github.com/azenyx/Semi-Advanced-Discord-Bot/blob/0598fdb320bb0c793004dddab4839efe72b56b78/Bot/utils/ipc_routes.py
Though ALL the code is not getting updated so with this you can get the hang of it but i do recommend making your own IPC or API.
ok how do i make my own API?
hey guys, does anyone know how I can retrieve all messages in a channel that were sent in the last hour? iv been trying to do it for ages but I cant get it working.
You did do it with cogs right?
i dont want cogs
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
You don't have to but i do recommend it since it will be very difficult to read.
Use after param
You using repl.it?
omg ty
Do make a check though if in this channel for example you go trough all messages of the last hour it's going to take awhile.
Then why the dislike of cogs :3
Cogs are good 
Suggest more topics here!
cogs
Suggest more topics here!
Not force them to move to slash commands
how would i make a command that removes a role from everyone who has it
!d discord.Role.members
property members: List[Member]```
Returns all the members with this role.
@dire folio
i dont know i just dont understand it maybe
'git' is not recognized as an internal or external command,
operable program or batch file.``` i wanna add a depoisitory but it wont work
How do i add it
@cloud dawn
Guys pls help I can't find an uptime command without cogs
Then use cogs
I can't learn how to use them
Why?
Install git
They're difficult and English is not my main language so I don't understand them completely
Just create a variable on startup
Don't know variables too. I'm new : D
Then i recommend studying Python more first, this is not a library for complete beginners.
Ok
Well I edited the cog settings to remove them and the uptime cmd works fine...
I have this code, and in theory, as soon as a member joined the server, it would give a role. But that's not happening. Can anyone help?
@client.event
async def on_member_join(member):
role = discord.utils.get(member.server.roles, name = "teste")
await client.add.roles(member, role)```
client.add.roles?
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
This is what you're looking for
No
oh
You use use member which is your discord.Member object
And I would suggest you actually read the docs I sent
You'd use self instead of MyClient for get_channel as self is the instance not the class
Thank you changed, still my problem persists
Just ask your question
Anyone?
import datetime
from discord.ext import commands, tasks
class Dates(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
current_time.start()
@tasks.loop(hours=1)
async def current_time(self):
now = datetime.datetime.now()
now = now.strftime("%d/%m/%Y às %H:%M:%S")
channel = self.bot.get.channel(914569334985216060)
await channel.send("Data atual: " + now)
def setup(bot):
bot.add_cog(Dates(bot)) ```
why bro
self.current_time.start()
!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)
Also recommend to start it in the init and not on_ready.
I know, I'm just doing a test
Oh okay i assume the self thing worked.
solved one part but gave problems in another
channel = self.bot.get.channel(914569334985216060)
AttributeError: 'Bot' object has no attribute 'get'
It's an underscore
get_channel
Pip install git?
Trying to make a testmode command so that my bot will only respond to me. Already have some commands that only I can use with is_owner() but I can't find a way to lock all commands to be able to only be ran by me when I run testmode
hmm
async def on_member_ban(self, member: discord.Member):
channel = self.bot.get_channel(814956709290049596)
if not channel:
return
await channel.send(f"{member} was banned
!")```
when someone gets banned i want the bot to say user was banned
You could make cog checks.
Just override on_message and only process_commands if the message's author id is the same as yours
but nothing happens
Can someone explain to me why the bot stays on, puts a custom status but does not respond to commands?
import discord
import random
from decouple import config
from discord.ext import commands
client = discord.ext.commands.Bot(command_prefix = "?", help_command = None)
# <-- Eventos -->
@client.event
async def on_ready():
activity = discord.Game(name = 'PokéCenter no topo! Prefix: ?help', type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
print('Pronto para uso {0.user}' .format(client))
@client.event
async def on_message(message):
if client.user.mentioned_in(message):
await message.channel.send("**:pika_style: ・ Ei, meu prefixo é ``?``, use ``?help`` para mais informações!**")
# <-- Comandos -->
@client.command(name = "ola")
async def ola(ctx):
await ctx.send(f'Teste {ctx.author}')
@client.command(name = "dado")
async def dado(ctx, numero):
variavel = random.randint(1,int(numero))
await ctx.send(f':game_die: | {ctx.author.mention} E o número que você rolou é **{variavel}**!')
@client.command(name = "help")
async def help(ctx):
embed = discord.Embed(title=":mailbox: ・ Veja abaixo minha lista de comandos!", colour=discord.Colour.green())
embed.add_field(name="``?help``", value=" :setagreen: Mostra todos os comandos e suas funções do bot", inline=False)
embed.add_field(name="``?dado (número)``", value=" :setagreen: Escolhe um número aleatório de acordo com o número escolhido", inline=False)
embed.add_field(name="``?startl``", value=" :setagreen: Mostra a tierlist dos melhores iniciais para pvp! (Atualizado)", inline=False)
embed.add_field(name="``?gymtl``", value=" :setagreen: Mostra a tierlist dos melhores ginásios da PokéCenter! (Atualizado)", inline=False)
embed.set_footer(text=f"PokéCenter | Mensagem requerida por {ctx.author.name}")
embed.set_thumbnail(url=ctx.author.avatar_url)
embed2 = discord.Embed(title=":correto: ・ A minha lista de comandos foi enviada em seu privado!", colour=discord.Colour.green())
await ctx.send(embed=embed2)
await ctx.author.send(embed=embed)
await ctx.message.add_reaction(":correto:")
@client.command(name = "startl")
async def startl(ctx):
await ctx.channel.send(file=discord.File('imgs/iniciais1.png'))
@client.command(name = "gymtl")
async def gymtl(ctx):
await ctx.channel.send(file=discord.File('imgs/lideresgym.png'))
# <-- Configs -->
TOKEN = config("TOKEN")
client.run(TOKEN)```
(The code is not mine, it's from a person I'm trying to help who doesn't speak English and I got confused too)
So i read the docs on what checks were. It seems like that would work but I'd need the bot to be in a perpetual state of checking if the author is me when I put it into testmode.
@tranquil badge
@cold sonnet
anybody have a code example of a command using buttons with dpy 2.0? just switched up to 2.0 and the third party components dont work anymore.
!disnake eeeeee
panda
Hmm?
can you help me?
I looked at it idk.
Does the bot work if you don't do a custom status?
Oh didn't see that. yea that'll definitely work
I took that part of the code out and it still doesn't work
It's not that it doesn't work. It works. It's just not responding to commands
Just gotta figure out how to implement
For example, when I ping him, he answers me. But when I try to run a command, it doesn't respond.
O right didn't see the on message
@slate swanhttps://discordapp.com/channels/267624335836053506/343944376055103488/794484840078376976
oh
ty
it work
@cloud dawn is there an example for process_commands? I can't think of how to implement it
Thanks
That was over 24 hours ago
I know
just clone it
Wdym
How do I create a leaderboard command? I have seen videos on that topic on YouTube, but I don't really get it. If you don't mind, kindly explain the code to me, and I use json to store everyone's data.
But json is sync code.
Wdym
!blocking
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!
But I used json to make an economy system, and it worked. (PS: I'm new to coding with Python)
so i have a command where the user can setup the bot, but they need to input roles. How can I check to verify that those roles exist?
PLEASE PING IN REPLIES AND IF YOUR TALKING TO ME IN GENERAL
!dictionary
Check if they are roles by type hinting the arg they are converters.
how do you suggest i do that? also, PLEASE ping :(
Can someone help?
self.restart_bot as it's a method of your class. Also you aren't actually closing the bot itself before resetting so that would mean you get two processes
Just regular typehint ```py
@bot.commad()
async def test(ctx: command.Context, role: discord.Role) -> Optional[Message]:
but i want it so they can do !setup channel #channel or !setup role @role
How do user "setup" the bot?
group the commands
how do i do that?
I just wanted it to restart so that the code would update without me having to click the button every time I changed something
and thanks btw
I always forget the self
it doesnt seem to work
!d discord.ext.commands.group
@discord.ext.commands.group(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
This is similar to the [`command()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.command "discord.ext.commands.command") decorator but the `cls` parameter is set to [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group") by default.
Changed in version 1.1: The `cls` parameter can now be passed.
@cloud dawn
Yea, but you don't close the bot before you start a new process. Meaning you'd have two processes with the bot online in both of them. Making commands repeat etc, basically undefined behaviour sorta
if the restart_bot method doesn't care about the instance make it a staticmethod
git clone https://github.com/DisnakeDev/disnake
I recommend using the reload options from discord,py
If you are using cogs.
@bot.command()
async def check(ctx):
role = discord.utils.get(ctx.guild.roles, name="x")
if role in ctx.guild.roles:
await ctx.send("The role is on the server. ")
else:
await ctx.send("The role is not on the server.")
X is represented as the name of the role, and the indents might be out of proportion due to me being on my phone.
Tho I don't use discord.py anymore.
too late... after what the other guy said i deleted it to use something else...
Oh okay
I will study more about it tomorrow, thanks
thanks for the advices @slim ibex and @pliant gulch
pov you can't install a library
lmao
ok im comming back to this idea. but how can i check if they mention the role? it works when I say the role name, but not when I ping the role
I'm going to write the code on my phone rq
kk
@slate swan i dont wanna be nosy, but are you done?
role will always be in ctx.guild.roles if urs using discord.utils.get. if its not it will return None
Python on android is giving me a headache, I'm in class rn so that's why I can't code on my laptop.
kk i can wait
try typehinting role to discord.Role
I think it's because I downloaded nextcord instead of discord.py
Nvm I used the wrong token, I'm so stupid smh
Hi
I made it a variable so that I don't have to write more code
wdym
Instead of if discord.utils.get(ctx.guild.roles, name="x") in ctx.guild.roles, I made it a variable to lessen what I write
@bot.command()
async def check(ctx,roles: discord.Role):
role = discord.utils.get(ctx.guild.roles, name=roles)
if role in ctx.guild.roles:
await ctx.send("The role is on the server. ")
else:
await ctx.send("The role is not on the server.")
@frank tartan
no
Wait lemme make it better
dont use discord.utils.get
Why
role converts it to discord.Role and if its not in the server it raises an error
ty
im just saying thats a lot more code than you need
The utils.get here is completely un-needed
yeah
typehinting roles to discord.Role already internally runs a role converter
So roles would be a discord.Role object already
@bot.command()
async def check(ctx,roles: discord.Role):
role = roles
If role in ctx.guild.roles:
await ctx.send("The role is on the server. ")
else:
await ctx.send("The role is not on the server.")
Wait
roles has to be in the server otherwise it will raise an error
Since it's using the role converter
andy is correct
I see i see
Just make a command specific error
And check if it raises the NotFound or whatever error it was
!d discord.ext.commands.RoleNotFound
exception discord.ext.commands.RoleNotFound(argument)```
Exception raised when the bot can not find the role.
This inherits from [`BadArgument`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BadArgument "discord.ext.commands.BadArgument")
New in version 1.5.
I just want to learn how to make a chatbot
Or an interactive bot
I tried making a 2 player game with global variables, but once other people used it simultaneously, the bot broke.
Should I use a file to store the players' names or ids? @pliant gulch
so
Does it work?
=yes
Nice
IDs, because names can change but IDs don't
yes but i ran into an error while saving it to a json file
TypeError: Object of type Role is not JSON serializable i get this error and i have no idea what it means
Try not storing it in a file if I'm thinking correctly of what you are doing. Try using an actual database
no like
You cannot store a Role object in a json
I see i see
i have a command that saves it to a json file, but when i run it i get the command
Just not logical nor is it how it should work
how can i fix that???
how might i do that?
Access the property on the role object
Then don't code on the phone, is not recommended
I can't access my laptop due to me being in class
ok i figured it out @pliant gulch ty
I have got no other choice
Wait, so what are you trying to do?
then dont code
Just wait until class is done, that's it
@slate swan why u here again 
i wanna make it so that you can do !setup_teams @team_role, then it will save the team role to a json file. This is because I am working on a custom signing bot template
I'll just suffer not coding
I see i see
Well goodluck
can i not🧍♂️
you can not
why
Federal reasons
So... I am using this for users to ban people on the server using their id, but idk how to implement a try and exept block so if the user enters a wrong id it says "user not found"
is there a correct way to do this?
thats very wrong.
lmao I know
on_command_error is an event, not something you can just accept
yeah I for some reason thought that would work
and use a member object, rather than converting the id parameter to a discord.User Object, and plus, you call the API for every user which is unnecessary
wdym member object
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User") instances too.
hash(x) Returns the member’s hash.
str(x) Returns the member’s name with the discriminator.
bot.fetch_user() returns the discord.User object, which doesnt have a ban method.
ah you're unbanning
yea
when I run
@client.command()
@commands.has_permissions(administrator=True)
async def currentSettings(ctx):
with open("channels.json", "r") as fp:
chanData = json.load(fp)
with open("players.json", "r") as pl:
plaDada = json.load(pl)
with open("teams.json", "r") as ts:
teaDada= json.load(ts)
i get this error.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Extra data: line 1 column 21 (char 20)
{"Offer": "Not set"}{"transactions": "Not set"}{"demands": "Not set"}
that is in channels.json, the others just have []. I know the problem, but have no idea how to prevent it. Because I put stuff into the json files using this command
@client.command()
async def saveSettings(ctx):
with open("channels.json", "w") as file:
json.dump({"Offer": offerChannel}, file),
json.dump({"transactions": transactionChannel}, file),
json.dump({"demands": demandChannel}, file)
with open("teams.json", "w") as file:
json.dump(teamList, file)
await ctx.reply("I have saved all settings.")
assuming you're using discord.py
your solution would be to use a database to store data, not json.
but databases arnt working for me, so im using json
- That's not valid json.
- Use a database
- find me a database that actually works
- how can i make it valid? ik its invalid... but thats how json put it in there
aiosqlite (SQL)
ayncpg (PostgreSQL)
motor (MongoDB)
mysql
sqlite
postgresql
MongoDB
redis
- https://jsonlint.com/. You have multiple json objects next to each other, you should just use one object
{
"Offer": "Not set",
"transactions": "Not set",
"demands": "Not set"
}
JSONLint is the free online validator and reformatter tool for JSON, a lightweight data-interchange format.
for 1, ive tried those. they dont work. for 2) ik its invalid... i didnt even put it there.
with open("channels.json", "w") as file:
json.dump({"Offer": offerChannel}, file),
json.dump({"transactions": transactionChannel}, file),
json.dump({"demands": demandChannel}, file)
with open("teams.json", "w") as file:
json.dump(teamList, file)
put it there
well beacuse you're dumping it multiple times. Just dump one dict.
not sure why it's appending it tho, thats a bit weird
Put a {} in the file also
how do you suggest i do that?
then how do you suggest i import and export stuff using a dict?
well first of all, use a database, but you can just dump one dict like this
my_dict = {"key":"value", "2ndkey":"2ndvalue"}
json.dump(my_dict, file)
i still get the same error, but this is in the json file
{"offers": "Not set", "transactions": "Not set", "demands": "Not set"}
Can you send the full error? It looks like you're opening a few json files, so it might not be on the line you think it si
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user\OneDrive\Desktop\league bot template\main.py", line 86, in currentSettings
plaDada = json.load(pl)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 293, in load
return loads(fp.read(),
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 351, in _run_event
await coro(*args, **kwargs)
File "C:\Users\user\OneDrive\Desktop\league bot template\main.py", line 32, in on_command_error
raise error
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Looks like it's happening on line 86
plaDada = json.load(pl)
check whatever json you're loading there
The json does not have a {} probably
ik
but how do you suggest i fix that?
Do it manually
oh...
but I want to save settings using commands... not manually
do you have a suggestion on which database i should try?
anyone know what i can use to change the text under the bot profile
like Listening to spotify for an example
just my own thing
You can do that by changing the bot's activity status. What library?
activity = discord.Game(name="STATUS YOU WANT HERE", type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
that should work, its what i use
i was just looking for the function in python
to change the bots text
Sqlite is An offline locally saved and easy to use db
Well... what library? Python dosen't have them by default
tried it, didnt work
ex. discord.py
in what way did it not work?
wym what library
Didn't work is not a thing , "I was unable to learn it" is
it did not work
theres more functions that do the same thing?
try to use what i suggetsed
activity = discord.Game(name="STATUS YOU WANT HERE", type=3)
await client.change_presence(status=discord.Status.online, activity=activity)
like do you use discord.py, nextcord, disnake.py, etc
woop
no worry
that should work though
Yeah, then you should be able to use activity status like here
you can*
it works on my bot
there are also more than that
https://discordpy.readthedocs.io/en/stable/api.html?highlight=activity#baseactivity
You don't need use everything given in the docs ,
Just use the params u need
Like activity and status
also i wonder how does sql fetch data in python
like is it always an array of stuff
i'm just grabbing a number and using cursor.fetchall()
is it possible to use an array in @commands.has_any_role("admin")?
say @commands.has_any_role(my_roles_list['roles'])?
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
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 the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return True.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
@commands.has_any_role(*my_roles_list)
Would this work for my list?
What does your list look like?
Is that a part of a dict?
Then you want to get that key's value, then unpack that
*that_dict["roles_baninfo"]
Yes I'll be targeting that specific part
My variable will look like this:
myvariable = mydictionary['roles_baninfo']
fetchall is most SQL databases returns a list of tuples
Then you want to unpack myvariable
is it possible to get the id of a role using its name?
im just trying to figure out how to get the id of a role
You could try
role = discord.utils.get(guild.roles, name="Role Name")
```if you're using something based off discord.py
nice ty
Thank you! It worked
What's the documentation to look up for limiting a command to a specific channel
Well, I think you would need to write your own conditional for that
discord.py dosen't have a decordator for it
😦
you could make your own check though
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=nsfw#checks
how would i assign a role to a user by using their id
are you passing the user mention into the command?
Or is the bot doing it on join?
The targeting method changes based on how the command triggers
I sent a message earlier about trying to make a test mode command that only i can use and prevents anyone from being able to use regular commands.
@bot.event
async def on_message(message):
owner_id=352986404621647873
if message.author.id == owner_id and message.content == '!testmode':
channel = message.channel
await channel.send('**`Now in test mode.`**')
await bot.process_commands(message)
With it set up like this it prevents all commands.
Could I do a normal command like
@commands.command(name='testmode')
@commands.check(on_message):
I'm probably miss understanding something about this
If you're doing on_member_join
then you want to target the member part. https://discordpy.readthedocs.io/en/master/api.html?highlight=on_member_join#discord.on_member_join
If you're doing a command, then you want to use the mention functionality when you call the command. member : discord.Member in the command thingy
and simply get their info by that.
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s.
You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
get the user or use a arg and use the coro
This is close, but logically not correct. It would only run commands if the message content is !testmode thus would only work for that and not other commands. You want to set a bot variable to be a bool E.g bot.test_mode and then check if test_mode is True instead of message.content == !testmode
You can get the user using one of the methods I mentioned above.
This would mean you also would make a command that sets bot.test_mode to False or True in order for this to work
!d discord.ext.commands.Bot.get_user
get_user(id, /)```
Returns a user with the given ID.

for the command section, what would i need to pass following discord.Member , or is discord.Member by itself, a value
Again, it's about how he wants to do it. he still needs to get the specific user lol.
i want to make a bot command that will respond to a direct message, how do i do this?
async def kick(self,ctx, member : discord.Member, *, reason = None):
if reason == None:
reason = "No reason given."
await member.kick(reason=reason)
``` In this instance, 'member' is the variable and you're just pre-defining it to be a discord.member item
he said get the user by id
oh yeah
member is an argument and you dont pre-define its a type hint
Yes. it's a case of how does he want to grab it? is he parsing it through the variable specifically? or is he just doing an @ ?
or is it on member join? or does the bot grab every member in the discord and assigns roles?
Aight. I'll remember that.
I've always thought it was a pre-define
type hints do not alter run time
Anyway. it's still about how he's grabbing the member. at which step does he need to worry about?
!e
def function(name: str):
return print(name)
function(1)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1
I dont mean to spam but: i want to make a bot command that will respond to a direct message, how do i do this?
Like the first time I dm the bot, it will send one message. The second time, it will send another. Then the third time another message...
Alright, so once it's in a true or false state, what part would be actively be checking if that user can run commands?
The same code you had earlier in the on_message but instead of message.content == ... you'd do and bot.test_mode is True
tbh you can just add a default value of a string and not None or do if reason is None: or if not reason:
question, how do i toggle allow anyone to mention this role in dpy
Or reason = reason or "default", but the best choice is just to give it a default value in the command signature like you said
yeah
can someone please answer my previous question
if someone were to dm a bot twice, is there any way to change the message the second time someone dms?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [`AsyncIterator`](https://discordpy.readthedocs.io/en/master/api.html#discord.AsyncIterator "discord.AsyncIterator") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
check if the dm channel has a history with a message sent from user
thank u sm ill check it out
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
what would you fill in for the first three dots?
the time?
or number of messages
@slate swan
you can put message because you are iterating through messages
wait i am so sorry
i want to dm a bot once, get one message. Then the second time i dm it, i want to get a different message
is this possible?
Couldn't i just set this to a False with on_ready() then change the state with a regular command and use is_owner? I already have owner specific commands. I'm still confused how I would allow myself to still do commands though. Sorry for being difficult.
anyone know how to get the position of the bot in the role hierarchy
Setting it up the way I have it blocks my commands also.
Like give it a role?
i mean to get the position of where the bot sits in the role menu
I'm using Pycord with this code to get any event I want:
event = ctx.guild.get_scheduled_event(int(eventid))
if event is not None:
users = await event.subscribers(limit=100).flatten()
but I get this error:
in get_scheduled_event_users
'before': int(before),
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'NoneType'
https://docs.pycord.dev/en/master/api.html?highlight=event subscribers#discord.ScheduledEvent.subscribers
It doesn't say to specify before...
So do I need to do it now or not???
Just get a tuple of all the roles in guild and search for the index of bot's role in the tuple
So as long as you can set the variable True or False. You just need to make sure your logic is correct inside of the on_message, you still need to process_commands in the case where test_mode is set to False
That's why it's blocking all your commands, it's because you aren't handling that part
Anyone know how to make an inventory for the bot and if you catch anything, it adds it into your inventory
How would I remove multiple roles from a member? Would I need to get all roles for each command and then use remove_roles( role1, role2, etc)?
Database, like sqlite or postgresql
Though I think mongodb might be easier to model that type of data
"*roles (abc.Snowflake) – An argument **list ** of abc.Snowflake representing a Role to remove from the member."
So I would need to get all roles for each command?
Can I get them globally once somehow?
you can pass in the IDs
Oh!
as a list
Okay thanks
np
how to make cooldown
how can i get the guild id in the on_guild_remove() event?
The guild’s ID.
Getting this error
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/app/plugins/Cordila/cord/bfping-main/bfping.py", line 13, in gaw
await ctx.author.remove_roles(855877108055015465,723035638357819432,790290355631292467)
File "/app/.heroku/python/lib/python3.9/site-packages/discord/member.py", line 822, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/app/.heroku/python/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'int' object has no attribute 'id'
when I tried doing this
await ctx.author.remove_roles(855877108055015465,723035638357819432,790290355631292467)
you need to remove role objects
yeah thats what I thought, it is possible to define them once in a cog so its not repetitive for each cmd?
discord.utils.get(iterable, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Examples
Basic usage...
any its ot but what happens when sql cant find a table?
you mean what error is raised?
how to check if a message has attachment.
!d discord.Message.attachments
A list of attachments given to a message.
ok thank
You can also just construct discord.Objects with the IDs of the roles
Since remove_roles takes a snowflake
uhhh i forgot
yeah but I would have to do it for each command right? 3 times for each command makes it cumbersome. How do I do it just once and then use the role obj for all cmds?
andy can you help :((
How would I do that?
!d discord.Object
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
ooh thanks!
Would just show an error saying it couldn't find the table
i'm pretty sure he wants to handle that error ^
how would i do something on it?
Are you trying to make a default value in your database if it isn't found?
like a try and except
no like what if a column isnt found
try-except the error then
can i really do that🧍♂️
ah it's OperationalError @slate swan
so the error raises as a traceback in your terminal🧍♂️
omg its aiosqlite ofc it will raise errors🤦♂️
sorry guys i had a bit of a brain fart
yeah specifically you should see something like sqlite3.OperationalError: no such table [table name] but yeah you can handle it
yeah sorry i had a bit of a brainfart
How do I create channels on command?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
Yep :(
hello
self.FFMPEG_OPTIONS ={'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'. 'options': '-vn'}
is the syntax correct
hi diabolical
this uses ydl right
yes
!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)
tldr it violates YouTube ToS and we can't help with that
Nooe
should i not use it ?
ok
thanks
so i am not going to use that
when I make an on_message function using nextcord, why does it keep on looping?
what should i use to make a music bot 😅
wdym by looping?
Nothing
It's against YouTube's tos
@client.listen("on_message")
async def filter(message):
await message.channel.send(message.content)
pass
🥲
this is the code I have rn
non copyright music is the only thing not from yt
yes
on each msg it will send a msg no matter the author
that means no no for music bot
on_message is for every single message posted
which the bot sends the msg so it will loop itself
Oh I see I see
you need to check the authors id
and no need for the pass
yeah, i was trying to say the bot's message is a message too
yeah
what is the pass used for
ignore
it doesn't really do anything
if message.author == client.user
Thank you
That would only check if the author is his bot
yeah, what should I use then?
oo
!d discord.abc.User.bot
If the user is a bot account.
returns a bool
!d discord.Member.bot
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/master/api.html#discord.User.bot "discord.User.bot")
😅
It's an aliase
yeah
i had one more question
probably because theirs user and member
like i used member.joined_at for showing the join date and time of when the user joined the server
what should i use to show their discord join date
!d discord.User.created_at
property created_at: datetime```
Returns the user’s creation time in UTC.
This is when the user’s Discord account was created.
thanks water

how do i add a emoji for presence on my bot
you mean activity?
i tried Activity(), CustomActivity()
await bot.change_presence( status = discord.Status.online, activity = discord.Activity(emoji = '🔥', name = str(amount) + "/" + str(max) + " Online!", type = 2))
this gives me an error
class discord.Activity(**kwargs)```
Represents an activity in Discord.
This could be an activity such as streaming, playing, listening or watching.
For memory optimisation purposes, some activities are offered in slimmed down versions:
• [`Game`](https://discordpy.readthedocs.io/en/master/api.html#discord.Game "discord.Game")
• [`Streaming`](https://discordpy.readthedocs.io/en/master/api.html#discord.Streaming "discord.Streaming")
Is using 2 optional arguments in a command hard to implement checks for or am I just doing it wrong
doesnt have such a kwarg
it does have emoji wym
nvm it does give me a sec
What is the best / most performant Async ODM for MongoDB?
i think its not possible
it must be a discord thing
cause i haven't found a bot with an emoji yet
!d discord.PartialEmoji is its type
class discord.PartialEmoji```
Represents a “partial” emoji.
This model will be given in two scenarios:
• “Raw” data events such as [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add")
• Custom emoji that the bot cannot see from e.g. [`Message.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message.reactions "discord.Message.reactions")...
how am i suppose to use this
await disconnect(*, force=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Disconnects this voice client from voice.
maybe just set it in the text as :fire:
but what arg
just in the text
name = '🔥' gives me an error
the activity name?
yeah
i was trying to figure out how to add custom status too
it wasn't letting me do a custom one
in your bot like not a game etc?
bots cant
Bots can't have custom statuses
welp im going to go to sleep early gn
random color by?
embed = discord.Embed(title=member.name, description=member.mention, color=0x00FFFF)
in this
instead of cyan
a random embed color
yes
!pypi discordheximals
returns hexcode by name for discord.py and its forks
well my module has a random color function
which picks any color from 742 if thats what your looking for
yes
color=discordheximals.Color.random()
would be how it should look
thanks
that means nothing will be there within the brackets
yeah it takes no parameters
ok thanks 😃
yw
btw cute about section 
thank you cute profile picture
thank you
oki 
thanks
np
@client.listen("on_message")
async def lol(message):
if message.author != discord.Member.bot:
await message.channel.send(message.content)
pass
When I run this code, the message sent keeps on repeating.
Is there anything wrong with my code?
discord.Member is supposed to represent a Member object, don't just copy paste.
.bot returns bool
You have a member object in which is message.autor
@client.listen("on_message")
async def lol(message):
if message.author != message.author.bot:
await message.channel.send(message.content)
pass
or when I run this code
yeah I tried that
if message.author.bot is True:
return
message.author which is a Member object will never be equals a boolean.
Just check
if not message.author.bot:
I see I see
ah sorry i just thought you could since .bot returns bool but it makes more sense
this worked, thanks
I see I'm not the only one wasting my time at copying lots of stuff many times ^^
but why didn't it work when I did if message.author != message.author.bot
As I said
yeah it took 10+ hours
as you said
message.author returns a Member object. message.author.bot returns a boolean.
I see
Member will never ever be equals to a boolean.
I see thanks
but it was worth it 742 colors in total
https://github.com/kkrypt0nn/Wordlists/blob/master/README.md
The README.md was pain to make, took me so much time. Don't remember how many but I'd say at least 2-3.
teach me
It was literally all the time
- Move file in a folder
- Open file and see the number of lines
- Write
[Name](folder/file.txt) - Lines x
So much pain 
dang im horrible at readmes
im trying to do a on_member_join event inside of a cog but it doesn't send anything
do you have member intents on?
yes
and have you loaded the cog and is the event in the cog(indentations)?
yes
show the cog
@commands.Cog.listener()
async def on_member_join(self,member):
channel = bot.get_channel(738540358761316439)
emb=discord.Embed(description = f'Welcome to the server {member.mention}!', color = discord.Colour.random())
emb.set_thumbnail(url=member.avatar_url)
await channel.send(embed=emb)
await member.send("I hope you enjoy your time in this server! :slight_smile:")
try printing on the event
self.bot.get_channel
it should raise an error, you have an error handler?
no, i didn't have a error handler i think
but i added self and it work now
you havent properly accessed your bot object.
hey guys, why doesnt this work? I dont know it works sometimes, but now it just stopped working
@patent lark
¯_(ツ)_/¯
define not work?
.topic
Suggest more topics here!
Uhh bro, this is a topical chat
Anyone got ideas for my discord bot? It’s based on retrieving data, such as covid-19, weather, etc,
Retrieve more data. There are probably a multitude of data to gather and display.
So?
The point of the command is to get a topic, related to Discord bots, to talk about instead of not talking at all or about something not related to Discord bots.
So there's absolutely nothing wrong about using it here.
class EmbedFlags(commands.FlagConverter):
title : str =None
description: str```
Can I make this accept either `title/description` **or** `t/d` as a short form?
Ah, I thought it gave random topics to talk about. Sorry bout that
The topic command always gets a random topic related to the current channel.
anyone?
The class?
As py EmbedFlags(title="SmThIng")?
Sorry I meant like if i have a command
@commands.command()
async def embed(self, ctx, *, flags: EmbedFlags):
embed = disnake.Embed(title=flags.title if flags.title else '', description=flags.description)
await ctx.send(embed=embed)
Is it possible that I can do either one of the below
>embed title:[title] description:[description]
or
>embed t:[title] d:[desciption]
I don't really think anyone knows about the answer to the question, Diabolical
ah i guess it's not possible?
maybe i can make two flag classes and use union, actually
Yea u can try doing that
Orrr try doing something like title or t = None
Idk this doesn't even make sense
EmbedFlags is a custom converter right?
it's a commands.FlagConverter class
!d discord.ext.commands.FlagConverter
class discord.ext.commands.FlagConverter```
A converter that allows for a user-friendly flag syntax.
The flags are defined using [**PEP 526**](https://www.python.org/dev/peps/pep-0526) type annotations similar to the [`dataclasses`](https://docs.python.org/3/library/dataclasses.html#module-dataclasses "(in Python v3.9)") Python module. For more information on how this converter works, check the appropriate [documentation](https://discordpy.readthedocs.io/en/master/ext/commands/commands.html#ext-commands-flag-converter).
iter(x) Returns an iterator of `(flag_name, flag_value)` pairs. This allows it to be, for example, constructed as a dict or a list of pairs. Note that aliases are not shown.
New in version 2.0.
Ok
haha yeah that made no sense anyways I got it to work
@spring flax the only thing I can suggest is to overwrite __getattr__ in your custom class. I am sure the FlagConverter (or its another parent class if it has one) has that overwrited as well, so you could look for example
yeah that's fine, I just use this as an alternative
@bot.command()
@admin_only()
async def embed(ctx, *, flags : Union[EmbedFlags, ShortEmbedFlags]):
if isinstance(flags, EmbedFlags):
embed = disnake.Embed(title=flags.title if flags.title else '', description=flags.description)
await ctx.send(embed=embed)
if isinstance(flags, ShortEmbedFlags):
embed = disnake.Embed(title=flags.t if flags.t else '', description=flags.d)
await ctx.send(embed=embed)```
made two flag classes, one with title/description and one with t/d
Alright seems legit
1 cmd that I have is not working
and the reason is literally nothing.
The other day it was working not it isnt
let me give here
@client.command(aliases=["cmds"])
async def Helpme(ctx):
embed = discord.Embed(
title='Help',
dsecription='These are the commands available for use at the moment.',
color=0x000000)
embed.set_author(name="Vincent Viktor")
embed.add_field(name='v!Pingms',
value="Tells you your latency.",
inline=True)
embed.add_field(name="v!meme",
value='Have a good laugh, watch some memes.',
inline=True)
embed.add_field(
name="v!daww",
value='Happy animals make humans happy, Watch some happy doggos.',
inline=True)
embed.add_field(
name="v!caww",
value='Happy animals make humans happy, Watch some cute cats.',
inline=True)
embed.add_field(
name="v!paww",
value='Happy animals make humans happy, Watch some cute pandas.',
inline=True)
embed.add_field(name="v!nacc",
value='New currency system! Open an account now!',
inline=True)
embed.add_field(name="v!beg",
value='Beg to get money... Totally not cool but ok.',
inline=True)
embed.add_field(name="v!bal",
value='Check your bank account balance.',
inline=True)
embed.add_field(
name="v!coinflip",
value='Feeling lucky? Bet on coin-flipping and earn money.',
inline=True)
embed.add_field(name="v!work",
value='Earn money the right way, Work for it.',
inline=True)
embed.add_field(name="v!withdraw",
value='Withdraw money from your bank account.',
inline=True)
embed.add_field(name="v!deposit",
value='Deposit money to your bank account.',
inline=True)
await ctx.send(embed=embed)
No reason this won't be working
You mistyped "description".
ohhhh
It sounds like there's a bigger issue here
You wrote dsecription instead.
Because you should have seen an error
So if you didn't that means you're masking it somewhere
wait there's another command
And you should fix that as soon as possible
did not
I use replit btw it does not show errors
Which means you're masking it somewhere
Do you have an on_message event by any chance?
I can't say I've used it, but I highly doubt that
nvm @slate swan fixed it
All righty
@tender estuary Do you have error handling anywhere?
yep
Send your code for that
Also I'm pretty sure replit shows errors.
It absolutely should
does not the way VSC did
If it doesn't... well... why would anyone use it
Yes it does.
@client.command(aliases=['wd'])
async def withdraw(ctx, money: int):
cursor.execute(
f"SELECT wallet_amt FROM account_table WHERE user_id = {ctx.author.id};"
)
db.commit()
result_w = str(cursor.fetchone())
result_w = str(result_w).strip('[](),')
result_w = int(result_w)
cursor.execute(
f"SELECT bank_amt FROM account_table WHERE user_id = {ctx.author.id};")
db.commit()
result_b = str(cursor.fetchone())
result_b = str(result_b).strip('[](),')
result_b = int(result_b)
if money > result_b:
embed = discord.Embed(
title='Don\'t try to oversmart me.',
description='**You can\'t withdraw money you don\'t have.**',
color=0xff0000)
embed.set_footer(text='I mean come on that\'s common sense.')
elif money <= result_w:
result_w = result_w + money
result_b = result_b - money
cursor.execute(
f"UPDATE account_table SET bank_amt = {result_b}, wallet_amt = {result_w} WHERE user_id = {ctx.author.id}; "
)
db.commit()
embed = discord.Embed(
title=f'Account Balance.',
description=f'**:dollar: Money withdrawn from your bank account.**',
color=0x00ff05)
embed.add_field(name=f'Wallet', value=f'{result_w}', inline=True)
embed.add_field(name=f'Bank', value=f'{result_b}', inline=True)
await ctx.send(embed=embed)
You eventually have something not opened or you're not sending errors correctly.
doesn't for me
this does not work as well
@tender estuary Again, let's fix this error handling
Because you're just creating a headache for yourself
If you have an error handler you eventually blocked remaining errors from showing.
@client.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send(
f"No such command, {ctx.author.mention}. type v!cmds for available cmds!"
)
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f'Please enter all required arguments.')
elif isinstance(error, commands.BadArgument):
await ctx.send(
f'The command does not take that as the argument, {ctx.author.mention}.'
)
elif isinstance(error, commands.BotMissingPermissions):
await ctx.send(
f'I miss the permissions to perform that, Make sure to put my role at the top! {ctx.author.mention}.'
)
elif isinstance(error, commands.MissingPermissions):
await ctx.send(
f'You miss the roles to use this command! {ctx.author.mention}.')
elif isinstance(error, commands.CommandOnCooldown):
embed = discord.Embed(
title=f'Cool down before I burn you up.',
description=f'Try the command again in {int(error.retry_after)}s.',
color=0x000000)
await ctx.send(embed=embed)
what a mess embeds list like that lol, create a list of tuples of name, value and inline like this
embed_test_creation=[("name1", "value1", True)("name2", "value2", False)] #and so go on
for name, value, inline in embed_test_creation:
embed.add_field(name=name, value=value, inline=inline)
As you can see, all others errors are ignored.
You'd want to raise error at the end to make sure they all show.
@tender estuary You should have an else which raises the error
let me do it
help me with this please
We can't yet, we need to see the error first
Fix up the error handling, run your code again, see if you get an error this time
If there isn't one then we can start looking for logic errors
else:
raise error
``` ( ignore indent for now ) correct way?
Yep
did not
Did not what?
show any error
Right, so must be a logic error assuming you've saved and ran the new code
And also to mention
whenever I add something to the bot, this is the command which goes null
most of the time
So, what do I do
Do I rewrite the whole command
what timezone does message.created_at return?
property created_at: datetime.datetime```
The message’s creation time in UTC.
oh okay my bad thanks
can anyone suggest any unique utility commands? I ran out of ideas
I need them as well.
embed = discord.Embed( # Create embed message with current and max online.
title="[ZTK Приватный сервер]:\n`Версия 1.16.5`",
description=f"[**Онлайн:** `{cur_online.text} / {max_online.text}`] [**Айпи:** `{ip_server.text}`]\n Данные обновляются каждые
5-минут",
colour=int("0x2f3136", 16)
)
?
smth gave None, so it can't use .text
Sup guys
hlo
not familiar with azure tbh
I am having azure subscription
you can google it tho
discord.on_reaction_add(reaction, user)```
Called when a message has a reaction added to it. Similar to [`on_message_edit()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message_edit "discord.on_message_edit"), if the message is not found in the internal message cache, then this event will not be called. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") instead.
Note
To get the [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") being reacted, access it via [`Reaction.message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Reaction.message "discord.Reaction.message").
This requires [`Intents.reactions`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.reactions "discord.Intents.reactions") to be enabled.
Note
This doesn’t require [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") within a guild context, but due to Discord not providing updated user information in a direct message it’s required for direct messages to receive this event. Consider using [`on_raw_reaction_add()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_reaction_add "discord.on_raw_reaction_add") if you need this and do not otherwise want to enable the members intent.
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
why .id
look at the first line
you want msg2 variable as a message but it is something weird
!or-gotcha
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.")
File "main.py", line 31, in <module>
bot.load_extension("cogs.economy")
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.economy' raised an error: SyntaxError: invalid syntax (economy.py, line 151)
halpp
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 140, in on_message
await message.channel.send(embed = embed)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1065, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.fields.1.value: This field is required
help??
how to make my bot get the last 1000 voters and send them in an embed
code (embed needs value btw)
how to fix this
dk, no code we can;t read mind
Hey @zealous dagger!
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 i put value
click dat link
send code :l
HOw to use that
click dat link, and paste ur code, ctrl+s, send the link that the web generate here
Here you go
while True:
try: # try except is not required but i would recommend using it
event = await client.wait_for("select_option", check=None)
label = event.component[0].label
if label == "Option 1":
await event.respond(type=InteractionType.ChannelMessageWithSource,ephemeral=True,
embed=e1
)
elif label == "Option 2":
await event.respond(type=InteractionType.ChannelMessageWithSource,ephemeral=True,embed=e2)
elif label == "Option 3":
await event.respond(type=InteractionType.ChannelMessageWithSource,ephemeral=False,embed=e3)
except discord.NotFound:
print("error.")```
Here you go
It is showing
InteractionType
not difined
greatt
yes
if i not wrong, in this version InteractionType from button is removed (lemme getthe reference, wait)
🤷♂️
reaction maybe :v
Hey
oh
docs linkhttps://devkiki7000.gitbook.io/discord-components/change-log/2.0.0#breaking-changes
:l ok, not experienced on that, some ppl like sarthak_, or okimii might help
:l both off
@zealous dagger what library do you use
What version
I don't know how to use aany other
so, how
thx
reaction in menus might help :v
k
For example you could use dpy 2.0 or its fork (fork is better)
There are examples in examples folder on github
can u send all message in one?
Sorry man that's my habit
oh ok then :v
My code is of 350 lines
just a reminder that in this channel, slowmode enabled
The easiest to do right now is to install dpy 2.0, but it is no longer maintained
Check pins to know how to do that
You mean voters on top.gg or something?
They won't fit into the embed tho lol
yee (i alr use top.gg API last 1000 voters, i just wanna know how to print all the voters username)
Need to check their API docs brb
don't worry :) i just have around 9 or 8 voters (pity pls)
kek ok
i bet someone will think u r writing a novel
I can't find
@small igloo do you have any code right now?
there are too many of them
wait, lemme send
@bot.command()
async def last1000voters(ctx):
name = ctx.author.id
if name == 828182019841327115:
response = requests.get('https://top.gg/api/bots/879000165757890570/votes')
r = response.json()
le = len(list(r))
em = discord.Embed(title="last 1000 voters", description="", colour=ctx.author.color)
for i in range(le):
em.add_field(name=str(i + 1), value=f'{r["username"][i]}', inline=False)
await ctx.send(embed=em)
key error: 'username'



