#discord-bots
1 messages · Page 103 of 1
also, you're calling .format on the File and not the string...
good point
how
does it need importing?
!d io
Yes, but I’m pretty sure it’s reset when you load up your replit the next time
This channel is only for discussions related to discord bots, try asking in #❓|how-to-get-help
BRO THAT BREAKS TOS
what?
you tried !help but help command does not exist
Oh.
No it isn’t
I have multiple megabytes worth of json files
are they static configuration files? or user generated data?
I'm hoping it isn't the latter
No I use the write file
I have an economy bot
And it stores the days
view = nextcord.ui.View(timout=0/None)
if content_word == "test" and message.author.id in Admins:
map = Update(Faction)
bytes = BytesIO()
map.save(bytes,format="PNG")
map.show()
bytes.seek(0)
dfile = discord.File(bytes,filename="test_image.png")
await message.channel.send("{} SHUT THE FUCK UP! {}".format(message.author.mention,file=dfile))
Help i have no clue whats wrong
Use an f-string
whats an f-string
!f-string
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.
await message.channel.send(f"{message.author.mention} SHUT THE FUCK UP! {file=dfile}") ```like this?
You need to pass in file as a seperate argument of .send()
await message.channel.send(f"...", file=dfile)
thanks, but my filling is destroyed lmao (not ur fault)
If it works it works
How can I detect when a component has been interacted with (I'm using python3.9)
Pain.
well, that would first require reciving the input in the first place.. ties back to my question
if you've found out how to do that, please let me know
how did you detect when they clicked a button
please share an example
can you show me an example of how you detected the button press though?
Does anyone have any ideas how to do this
https://femboi.best/DVhgkBoi
i cant do bot.add_view(ReactionRoleView(menu=None, name=None) since theres a for loop inside the view so idk how
what're your trying to do?
@discord.ui.button(style=discord.ButtonStyle.red, custom_id='one',emoji="🥾",)
async def one(self, interaction: discord.Interaction, button: discord.ui.Button):
guild = interaction.guild
print(guild,interaction.user.id)
Error: None 1023653948123458718
why cant find the guild?
make it perma so after bot reboots
most cases i could just do bot.add_view(ReactionRoleView(menu=None, name=None) but since theres a loop right inside the view i cant
i am
that just sets no timeout, not on reload & reboot
look at the code?? i cant run None thru a loop
oh, right. Why are you passing None in the first place then? And if for some reason that makes sense in your head, pass in an empty list instead of None
wdym?
thats what your supposed to do lol
and i cant pass a empty list i dont think since the view will be edited to none then
I wouldn't think so. Apparently, you're trying to make reaction roles with buttons, so I'm guessing menu would be the list of roles, and name would be, perhaps, the name of the guild, idk. You'd probably want to iterate through your "database" (which apparently is a JSON file and you shouldn't use that as a database), get the list of roles that you saved, and pass that to your view. Don't pass None, because you actually need a value
How would one go about adding a cooldown to responses? I’ve tried using the sleep command but it instead delays the response rather than stopping it all together.
interaction responses as a whole or slash commands?
Yes.
i figured it out but thanks
and im using mongo lol
Im just gonna store rolemenus in the db and instead of passing a list in and making buttons just access my database, passin the msgid from the cmd, and make buttons as needed
I gave you 2 alternatives, you're giving me a "yes" answer. That doesn't really help
The first one.
I don’t want the commands to be spammable.
Since the environment I plan on implementing the bot a lot of the people in that server jump the bot all at once.
You're gonna have to implement your own cooldown system for buttons and modals. For slash commands though, there's a check:
!d discord.app_commands.checks.cooldown
@discord.app_commands.checks.cooldown(rate, per, *, key=...)```
A decorator that adds a cooldown to a command.
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns are based off of the `key` function provided. If a `key` is not provided then it defaults to a user-level cooldown. The `key` function must take a single parameter, the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") and return a value that is used as a key to the internal cooldown mapping.
The `key` function can optionally be a coroutine.
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandOnCooldown "discord.app_commands.CommandOnCooldown") is raised to the error handlers.
Examples
Setting a one per 5 seconds per member cooldown on a command:
Thank you.
you're welcome
i figured it out but thanks
alrighty
im using mongo lol
ah, sorry
for the rest, the first idea that you had in mind was a good one, you just had to implement a storing and accessing system that fetches the roles with their corresponding button ids which you can then pass to your view
Can someone point me in the right direction to adding an option to a slash command? So if they use /level it shows their level, which I have already written. Or they can do /level: user=<user> to get someone else's level
Actually, nvm I think I just found it. We shall see.
Follow up: did not work as intended.
you can type hint Optional or add a default value
from typing import Optional
from discord import Interaction
@app_commands.command(...)
async def command(self, interaction: Interaction, argument: Optional[str]):
...
# or
@app_commands.command(...)
async def command(self, interaction: Interaction, argument=None):
...
# or both
@app_commands.command(...)
async def command(self, interaction: Interaction, argument: Optional[str] = None):
...
@discord.ui.TextInput(label="About Me" , style= discord.TextStyle.paragraph , placeholder = "Write here")
async def callback4(self, interaction: discord.Interaction , TextInput):
if interaction.user != self.ctx.author:
await interaction.response.send_message(f"Not your interaction" , ephemeral=True)
return
self.about_me = TextInput.value
await interaction.response.send_message(f"**ABOUT ME**\n\n{TextInput.value}" , ephemeral = True) ```
textinput is not callable ?
error ]
TextInput is a class you use with modals...?
@asher suggested me to make a views and interactions manager library for discord.py
I asked him multiple times but he not told what should it do
personally i don't think there's much need
there are already plenty of tools that do that
Actually I am asking whats meaning of interaction and views manager?
I will make this type of library for my practice
Not sure. I guess a library to use discord interactions?
It says manager
Ig like a store of views and we can access them from any file?
Like redux in react?
Maybe, probably not though
Might be better to work on something a bit easier and more feasible/useful
#databases pls
What is the problem on this code why not working
guild.member_count
not guild.member.count
Lemme try
Oh that worked thanks
if i have a list of messages i want to delete, which is better - channel.delete_messages() or purge() with a check?
by that i mean which is less likely to get me rate limited 💀
depends on how you're getting the messages to delete
purge() uses the channel history() to gather its messages, but if your bot already has the message IDs you want to delete, then delete_messages() will likely be the most simple
I think delete messages is better as it takes a list if I’m not mistaken
delete_messages() is always a single API call while purge() is at minimum 1 api call, that being querying message history, and any number of api calls afterwards to delete / query more messages
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
a+million+dollars
The command works in second try but sometimes it fails and i have to try again to make it work
If your command has to take over 3 seconds to respond, you have to defer it
And requests is blocking. Use aiohttp
how do i defer it
What's your library?
!d discord.InteractionResponse.defer - You could also use inter.defer. It's the same thing
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
Hello guys, I'm thinking of writing unit tests for my discord bot, but when I run the programme, it returns "TypeError: monthrn() missing 1 required positional argument: 'ctx'"
Here's the code:
import unittest
from unittest import IsolatedAsyncioTestCase
from datetime import datetime
import pytz
from cogs.time_cmds import TCmd
class TestTime(IsolatedAsyncioTestCase, TCmd):
async def test_month(self):
month = await TestTime.monthrn("monthrn")
await self.assertEqual(
month,
datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')).strftime("%m"))
if __name__ == '__main__':
unittest.main()
Can anyone help? Thanks.
Oh, sorry
It's a command that shows you the month as of now
I'm trying to writing a test case to see if it returns the right month
you'd need to subclass that, yes
Alright, thanks
direct = input("is the flight direct?: ")
flight1 = input("Is flight1 direct?: ")
flight2 = input("Is flight2 direct?: ")
direct: str(input("Is the trip direct or transit?: "))
flight1 = str(input("Please enter direct or transit"))
flight2 = str(input("Please enter direct or transit"))
flight3 = str(input("Please enter direct or transit"))
if flight1: ("direct")
print("flight1 is suitable for you")
if flight2: ("direct")
print("flight2 is suitable for you")
else:
print("flight3 is suitable for you")
low cost
cost: str(input("Is the flight cheap?: "))
flight1 = str(input("Please enter cheap or expensive"))
flight2 = str(input("Please enter cheap or expensive"))
flight3 = str(input("Please enter cheap or expensive"))
if flight1: ("cheap")
print("flight1 is suitable for you")
if flight2: ("cheap")
print("flight2 is suitable for you")
else:
print("Flight3 is suitable for you")
short time
Time: str(input("Is time long or short?: "))
flight1 = str(input("Please enter short or long"))
flight2 = str(input("Please enter short or long"))
flight3 = str(input("Please enter short or long"))
if flight1: ("short")
print("flight1 is suitable for you")
if flight2: ("short")
print("flight2 is suitable for you")
else:
print("flight3 is suitable for you")
I just want to tell you the idea of the project. I supposed to create a program for people who want to travel and there are three flights at the same time. The user must choose the best option in duration of flight, ticket price and if it is direct or transit. After he choose the program will suggest the best flight for him based on the options that he chose. Note: I have to use if nested in my code
Can you demonstrate it for me, I've subclassed the ctx one but I dont know what arguments to put in
just *args and **kwargs, pass that into super().__init__()
i think you just have to override ctx.send and/or ctx.reply
how do i sync commands in pycord?
It's auto-sync
I still dont understand, can you give me a code example
Sorry, Im still new to programming
The sync_commands always return None
https://docs.pycord.dev/en/stable/api.html#discord.Bot.sync_commands
that's a really broad question
What leaderboard? Wdym global? What does it do right now?
So how does your leaderboard work
In your code
the names in the brackets are the guild names
Not just the best players in 1 server
but you already have people from different servers..?
so what's the problem
you want X, but X already happens
you said you want ppl from different servers, but that's already what's happening is it not?
Oh this isn't yours?
ah
ok well how does yours work, codewise
Is it getting these from a db or?
I don't even know what this game is I can't guess what columns you need
You just need what you want to store
If this isn't connected to a db then where are you getting this data?
don't store names when you can store ids, names change
Yes
you'd use get_user
have you chosen a db?
From the discord.py server:
TL;DR: MySQL is a bad database. Don't use it unless you have literally no other option.
Why shouldn't I use MySQL?
- MySQL has no transactional DDL. This means that if you fuck up creating a table in the middle of a migration, you cannot rollback easily.
- MySQL has a lot of security issues. New zero-day vulnerabilities are found regularly.
- MySQL is owned by Oracle.
- MySQL is slow. It beats Postgres etc at some things, but once you move beyond basic queries it begins to slog.
- MySQL disconnects you randomly. Unless you setup your connection specially, it will break regularly.
- MySQL allows all kinds of insane data to be inserted. '0000-00-00' is valid in MySQL.
- MySQL is not ANSI compliant. You have to turn it on; even then it isn't fully compliant.
- MySQL has no feature advantage over other databases; PostgreSQL has many more useful features (such as RETURNs).
There is no reason to use MySQL over PostgreSQL, or even sqlite3. See also:
https://blog.ionelmc.ro/2014/12/28/terrible-choices-mysql/
https://grimoire.ca/mysql/choose-something-else
The terrible pitfalls I've gotten myself into while using MySQL — I've used MySQL for a while now, and there were lots of surprising things I needed to cater for. This is from a Django and MySQL 5.5 perspective...
- mysql is owned by oracle
how about Java and javascript
don't see any reason to not use mysql with a bot. unless you're doing some high-fi operations that only pgsql supports
- mysql disconnects ....
skill issue, use a connection pool, not direct connections
Nope
whats the issue?
Find an async library for it and look at docs/examples
the first thing you'll do is choose your driver
for async context you can use aiomysql or async with sqlalchemy ( relatively hard)
next you'll create a connection pool with the credentials of your host
later create the table with columns you need
!pip aiomysql
I mean it's your game, store whatever you need but that looks good
are you using a connection or a pool?
seems all set then, simply create ur table and proceed now.
You should decide if you want to have a composite pk of guild and user or just the user as a primary key
sure ping me when you need help
vs code keeps giving me indentation error
i don't anything wrong with the code
@slate swan
did you complete the function above that function?
yeah
mind showing that code?
i have a question
why does my cmd promt keeps repeating and iteration
that has already been done
if i add a licensing system
at the top of code
just re-start vscode, the code is fine
im assuming its because of the if __name__ == '__main__':
it's still gives me error
this is the code being repeated
does that say unexpected indentation or inconsistent use of tabs and spaces?
yeah
which one
this is desirable
unexpected indentation
this is repeated
that's weird, can you paste the file in a pastebin and send?
@bot.command()
async def prison(ctx, member: discord.Member = None, time = None, *, reason = None):
prison_role = discord.utils.get(ctx.guild.roles, name="Prison")
author = ctx.message.author.id
time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
if member == None:
await ctx.send("Please Mention A Member To Prison Him!")
elif time == None:
await ctx.send("Please Mention The Time You Want To Put!")
elif reason == None:
reason = "None"
tempmute = int(time[:-1]) * time_convert[time[:-1]]
embed = discord.Embed(title="Prison Member", description=f"{member.mention} Is In Prison. For {time}")
await member.send(embed=embed)
await ctx.send(embed=embed)
await member.add_roles(prison_role)
await asyncio.sleep(tempmute)
await member.remove_roles(prison_role)
when i do !prison @slate swan 20m dhsu
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '20'```
How would I get a bot to scan a predetermined channel ID?
So I can set it as a parameter for an if statement.
Would it be something like discord.channel.id?
No that doesn’t work.
I don't understand your question
The idea is to get it to only be able to respond in a predetermined channel based on its channel ID.
But I’m not sure what the library call is.
Or it if even exists.
cann someone help me w that
channel = bot.get_channel(channel_id) I think! i dont know if its true
like for me it works
I’ll try it.
okay
vs code has two type to do indentation A. 4 spaces B. a tab
i mixed my old code which was in (A) and used tab(B) in the new file
thats why it kept giving me error
It’s saying bot is not defined.
Oh.\
Thanks anyways though it was worth a shot and besides I learned something from it.
send the complete error log not just the commandinvokeerror
No prob!
[2022-10-09 10:48:59] [ERROR ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 487, in prison
tempmute = int(time[:-1]) * time_convert[time[:-1]]
KeyError: '20'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 165, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '20'
ok gimme a min let me try it
okay tysm
What's the problem
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Thank you.
Then what's the problem with that part
I don't know what you want, and that's not something I can help with
@bot.command()
async def prison(ctx, member: discord.Member = None, time = None, *, reason = None):
prison_role = discord.utils.get(ctx.guild.roles, name="Prison")
author = ctx.message.author.id
time_convert = {"s": 1, "m": 60, "h": 3600, "d": 86400}
if member == None:
await ctx.send("Please Mention A Member To Prison Him!")
elif time == None:
await ctx.send("Please Mention The Time You Want To Put!")
elif reason == None:
reason = "None"
tempmute = int(time[:-1]) * time_convert[time[:-1]]
embed = discord.Embed(title="Prison Member", description=f"{member.mention} Is In Prison. For {time}")
await member.send(embed=embed)
await ctx.send(embed=embed)
await member.add_roles(prison_role)
await asyncio.sleep(tempmute)
await member.remove_roles(prison_role)
when i do !prison @slate swan 20m dhsu
[2022-10-09 10:48:59] [ERROR ] discord.client: Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 190, in wrapped
ret = await coro(args, **kwargs)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 487, in prison
tempmute = int(time[:-1]) time_convert[time[:-1]]
KeyError: '20'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event
await coro(args, **kwargs)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 165, in on_command_error
raise error
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\bot.py", line 1347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 986, in invoke
await injected(ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ext\commands\core.py", line 199, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: '20'```
Key 20 doesn't exist in a dictionary
so i cant do for 20m?
You can't do for anything
what
so to remove the m?
youtube
tempmute = int(time[:-1]) * time_convert[time[1:]]
this should be the correct tempmute line and btw small tip but change the rest of the part like the dm stuff and all, maybe put it after the member is awarded with the role
ill try thanks!
np
That wouldn't work with any numbers higher than 9
!e
time = "20m"
print(time[1:])
print(time[-1:])
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0m
002 | m
doesnt work
idk about that, maybe put some limit or smthing
i just corrected the line
okay - i'll use it, ty
ty!
i see, thanks for the info!
i think to be clear that even dyno has a limit of 9hrs and not more and they have the whole h, s, etc. system
@bot.command()
async def mines(ctx, amount=None):
amount = int(amount)
if amount is None:
await ctx.reply('Must specify a value between 1-24\nExample: ``.mines 5``')
elif amount <= 24:
mines = 25*[':question:']
random_safe = random.sample(mines, amount)
for x in random_safe:
random_safe[x] = ':gem:'
row1 = mines[0] + mines[1] + mines[2] + mines[3] + mines[4]
row2 = mines[5] + mines[6] + mines[7] + mines[8] + mines[9]
row3 = mines[10] + mines[11] + mines[12] + mines[13] + mines[14]
row4 = mines[15] + mines[16] + mines[17] + mines[18] + mines[19]
row5 = mines[20] + mines[21] + mines[22] + mines[23] + mines[24]
percentage = str(random.randint(45, 90))
thumbnail = 'https://cdn.discordahttps://media.discordapp.net/attachments/1017329425513197568/1028582459941584978/E6998A39-624D-45C2-9002-B27FD399A776.jpg?width=1041&height=1055pp.com/attachments/1013865134504026112/1015741200722055289/standard.gif'
em = discord.Embed(color=0x11F1D3)
em.set_thumbnail(url=thumbnail)
em.set_footer(text="Made by Dewier")
em.add_field(name="Mines predictor",value=row1 + "\n" + row2 + "\n" + row3 + "\n" + row4 +"\n" + row5 + "\n" + "**Accuracy**" + "\n" + percentage +"%")
await ctx.reply(embed=em)
else:
await ctx.reply('Must specify a value between 1-24\nExample: ``.mines 5``')```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str
with delete_messages(), do i need to pass message objects or message IDs?
!d discord.TextChannel.delete_messages
await delete_messages(messages, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes a list of messages. This is similar to [`Message.delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.delete "discord.Message.delete") except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing is done. If the number of messages is 1 then single message delete is done. If it’s more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that are older than 14 days old.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this...
what do you want to do though?
it looks like it's message objects. thanks
you can also pass a normal discord.Object if you don't want to fetch_message all the time
await channel.delete_messages(discord.Object(id=1234))
wouldn’t be ideal tho no? All those api calls
if its about api calls using discord.Object would be lot better than fetching message objects just to delete them
you don't even need a discord.Object tbh, any object which has an id attribute set as the message id works
import random
amount = 5
mines = 25*[':question:']
random_safe = random.sample(mines, amount)
for x in random_safe:
mines[x] = ':green_square:'
print(mines)
print(f'\n\n\n{random_safe}')```
my bad, i used the wrong method above xd
TypeError: list indices must be integers or slices, not str help pl
I was so confused lmfao
yeah im high don't mine me
*mind
x is a string and you're trying to index a list using that
how doo i fix i havent slept in 30 hours
what do you want to do?
It turn the 5 random ❓'s into 🟩
how can i make a command that shows how many users are in all the servers my bot is in ? i tried len(bot.users) but that doesnt work
wdym "doesnt work"
ye it just gives random numbers
random numbers? such as?
bro that doesnt matter the thing is that it doesnt work
every time i run the command again it gives another number
what's your code?
?
i gave you it before
your full command
just that and an await ctx.send
and your member intents are enabled?
idk
?? how do you not know what intents you've enabled
well i dont remember ok but it is on
so you know the problem or ?
works for me fine
you just need to enable the intents
?
show me the code
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
token = os.environ['TOKEN']
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(intents=intents)
@bot.event
async def on_ready():
print(len(bot.users))
bot.run(token)
k
ye it works if i print it but i cant use it in a command
but it should work, can you show us an example of the output?
yes
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
load_dotenv()
token = os.environ['TOKEN']
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(intents=intents)
@bot.event
async def on_ready():
print(f'{bot.user} is logged in!')
@bot.command()
async def countm(ctx):
await ctx.reply(len(bot.users))
bot.run(token)
first didnt work but after some time it did
skill issue
the first never works
like seriously how come it works for others and not you?
it does work now just not right away
idk
e
it's because of the cache
too bad
lol
looks like discord isnt installed ig
check for any duplicate forks of dpy in your modules and install dpy
it should work then maybe reinstall pycord
u used an interaction as an input type for your slash command option
help
elif risk = 'low':
09.10 10:19:09 [Bot] ^
09.10 10:19:09 [Bot] SyntaxError: invalid syntax```
you really shouldnt be doing discord.py if youre still getting syntax errors
its a fairly advanced lib and not for beginners
Im just an idiot thoguht i had to ='s
property user```
Represents the connected client. `None` if not logged in.
Just get avatar from it
!d discord.ClientUser.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.ClientUser.display_avatar "discord.ClientUser.display_avatar").
whats ctx.user 🤨
pycord moment'
await ctx.edit_original_response(view=self,embed=embed)
is this wrong after a button click ?
Traceback (most recent call
last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "e:\Python Projects\Top War Unity Bot\Commands\Credits.py", line 62, in callback1
await ctx.edit_original_response(view=self,embed=embed)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 461, in edit_original_response
data = await adapter.edit_original_interaction_response(
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
ctx.interaction.original_message ig
you're taking too long to respond
You only have 3 seconds
yeah i got it, thanks
If I give my discord bot to somone to host and they start using it maliciously, if I change the token in Discord Developer Portal will they be able to still use it?
No
If they won't get the new token somehow - no
interaction.interaction.original_message
because you call your ApplicationContext as interaction. be consistent with names.
error?
Hey ! I just used "py -m pip install discord.py", in terminal it says that it is installed but it doesnt seem to work
What can I do ? 🤔
how many versions of python do you have
you're using an venv to run the file, did you install discord.py in the venv?
I just ran that command in terminal, nothing else. It usually worked like that
How do I then write the optional arguments into the base command?
@discord.ui.button(*, label=None, custom_id=None, disabled=False, style=<ButtonStyle.secondary: 2>, emoji=None, row=None)```
A decorator that attaches a button to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View"), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction") you receive and the [`discord.ui.Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") being pressed.
Note
Buttons with a URL cannot be created with this function. Consider creating a [`Button`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Button "discord.ui.Button") manually instead. This is because buttons with a URL do not have a callback associated with them since Discord does not do any processing with it.
How do you
how do you uhh
I'm not sure how to describe it
how do you layer the buttons? Like you have one button on top of the other
instead of them having the normal layout of moving it to the right?
Set the row
you use rows ( row kwarg in Button )
And how can I do that?
Nvm, figured it out. Thanks guys
Is it possible to make a button, but it doesn't do anything, and it's not clickable?
Disable it
thanks.
u can use ctx.me to represent the client
so it will be something like this ctx.me.display_avatar.url
Is it possible to leave a button blank?
No label?
u can use railway.app
Does that offer a free tier?
yup
Yes
How?
Set \u200b as the label
tysm
Are you using it?
Yay it works!
Tysm catgal.
Is that unicode for a space?
no i dont have any projects i need to host, i just run and test them locally
Zero-width character
mmm okay, thanks.
but railway.app does have a free tier with $5 credit per month the only setback is you have only 500 execution hours a month
Its only free for 500 hr
thats the only drawback in railway, other than railway i dont know any other free hosting sites
Okay
for railway.app you can either link a card to remove that limit or wait for the github student integration update and get a github student account and apply for that
Git hub is launching a vps ?
How does this look?
uh no i meant that you can wait for railway.app to launch an update which allows github accounts with student priviliges to bypass all limits, you will need a github student account tho for it
The button callback must have 2 parameters (or 3 including self)
How do i get a person's icon url?
First for interaction, second for the button
Tourner dans le vide, vide
Tourner dans le vide, vide
Tourner dans le vide, il me fait tourner
avatar.url
Alright, thanks.
❤️
class Accepte_Button_View(discord.ui.View):
def __init__(self, timeout = None):
super().__init__(timeout=timeout)
@discord.ui.button(label="Accepter la commande", style=discord.ButtonStyle.green, custom_id="Accepte_Button")
async def callback(self, interaction:discord.Interaction, button: discord.ui.Button):
if interaction.user.get_role(1014964643191607387):
Embedvendeuraccepte = discord.Embed(title="Commande prise en charge", description=f"**Vendeur :** {interaction.user.mention}", color = 0xfae893)
await interaction.response.send_message(embed = Embedvendeuraccepte)
self.children[0].disabled = True
await interaction.message.edit(view = self)
else:
await interaction.response.send_message("Tu n'es pas un vendeur Java pour accepter la commande. :(", ephemeral=True)
@slate swan
(don't spoonfeed, just saying)
wrong cht
Yes
It's only one argument
npnp
Is there any way I can make this look more appealing? Also the colors may look bleak because I have Night Light Mode on at 90% strength so ignore that.
what is this game? like the flushed emoji collects the apples?
Snake and yes.
Then the flushed emoji grows
You still making snake?
I am remaking it
I am trying to make everything more modular and more organized
I maintain that using pillow is the way to go
Pillow seems so hard
It scares me, it's intimidating
Also your salt miners is very cool
It's not as hard as it looks
How to get full input/larger input through a command
you can add a count for number of collected apples in the footer
Wouldn't it make more sense to have a snake length counter though 
Okay, I'll experiment with it, I'll make 2 modes of snake, one with pillow, one without, and I'll see what my friends like more.
Anyone ? It gets cut off at 45 characters
Idk what you're asking Wolfy
value should be same, so either way works
Like a string input?
yea, normal commands, string input
For a slash command?
no, just command
If you need more than 45 characters I would recommend using a modal
Idk how it's getting cut off if you're using message content commands though
oh, wasn't using content, whoops
thanks
i have a question can anyone help?
in an exe file the task in if name == main is being looped again and again
nothing else is being executed
any reasons??
We don't have any code, we can't help
ah okey I'll send some snippets
First Ss :- The code Itself
Second Ss - How it looks in a py file (works perfectly fine)
Third Ss :- How it looks in an exe file (repeats The Enter your license iteration)
@rocky trench
@tasks.loop(seconds=180)
async def check_activity(ctx, member: Member, client):
print("checking statuses")
role = client.guild.get.role(1014853981752795217)
for member in client.get_all_members():
if 'cpr' in member.activity:
await member.add_roles(role)
print(f"{member.name}#{member.discriminator} is repping")```
trying to make a bot that automatically gives a user a role if they have "cpr" in their status. I dont get any error but this code doesnt work any help would be appreciated
I feel like you can't use that in an exe
!d discord.Member.activity
property activity```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.
Note
Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.
Note
A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.activities "discord.Member.activities").
Client.guild doesn't exist, you probably have an error handler that's eating your errors

oo
any ideas why i getting 400 error>?
full traceback?
Have you tried executing all of that in a function?
yea it loops
That's odd
mhm
Have you tried coverting the file again?
If you have and it still has that behavior, I'm not sure, I've never encountered the issue really
i havent can u tell


👋
hey i need a bot that gets everyone's id inside of a server really fast
someone hacked the person that created the server
have him change his password
pretty sure the hacked already changed his password or smth
what are you going to do with their ids tho
invite them to a new server
bruh
you can't just send an invite link in a channel?
not 100% of the people will join the new server or even have their dms open
unless you did something like what restorecord protected servers do, they take the members authorization to auto add them in a new server incase current is nuked
but its prolly too late now
wdym with restorecord protected servers?
its a bot
built around your current issue
well there is a bot restorecord which just asks a new member which joins a server to verify by giving their authorization to the bot's application to auto add them in a new server incase the current one is nuked/destroyed
message.author.roles to get all the roles of the person who sent that message
You only passed in 2 values but there are 3 %s
Also shouldn’t you be using aiosqlite’s ? Instead of %s?
To avoid SQL injection attacks?
ah my bad, im trying to have the user @ a role and get it from that, not the actual author
You’re looking for the RoleConverter then
got it working, perfect thank you
is it actually cloning ?
cause if it’s not cloning anything then output would be none
also check if that function even returns a channel
where is the code that is using the output variable? is it in the same function?
that’s why
You defined Output in a completely different function
is there a specific reason for you storing the channels tho?
otherwise if so you need to rethink your logic
no like why tho, why are you storing that data? is it explicitly necessary to
if you do not need that data I wouldn’t store it. if you need it, then go back to your code and rethink your logic
I would suggest creating the temp channels when they join the join2create channel rather than having them use a command
how to fix
!pypi durations-nlp
ask them to enter a string
is that how everyone else does it?
code?
!pip time-str
better than durations-nlp?
yes , a lot in this case.
you just need to do ```py
async def command(ctx, argument: time_str.IntervalConverter):
await ctx.author.timeout(until=discord.utils.utcnow() + datetime.timedelta(seconds=20))
Am I doing something wrong?
You got an error?
btw does this follow conventions for project organization?
just not working
await timeout(until, /, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Applies a time out to a member until the specified date time or for the given [`datetime.timedelta`](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)").
You must have [`moderate_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.moderate_members "discord.Permissions.moderate_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Oh yeah
await ctx.author.timeout(until=datetime.timedelta(seconds=20), reason=None)
bad on_command_error moment
all on
you can't do until= here! its a positional argument
also, if you have an on_command_error event add else: raise error to it
error being your exception class
so remove until=
basically yes
ye idk still dont work
await ctx.author.timeout(datetime.timedelta(seconds=20), reason=None)

im using py cord and my slash commands aren't syncing in all the servers
cuz very bad code ( from pycord)
can you see a folder named discord in your venv's site-packages folder?
yeah
ok before everything, try syncing the commands after the bot has started
basically add that await client.sync_commands thing in on_ready or something
im literally doing that
you sure? you call load_commands before client.run() !?
im talking about the sync_command inside your load_commands function, that shouldn't be there
yeah i changed that already, i was trying different ways to just get it synced
so this is what ur code looks rn?
okay then back here
open the discord folder
go in http.py
line 280
replace self.__session. with self._HTTPClient__session.
in all the places?
just the line 280
also, what version of pycord are you using?
done
2.2.2
please try running the code now
so the error got fixed
what does register_commands return?
i mean what does the docs say about that
it registers all the commands of given list
Register a list of commands.
does any1 know how to fix his error? AttributeError: 'Message' object has no attribute 'autor'
author not autor
oh am stupid af
haha no worries
well then it seems like no new commands were registered
is there any command in your code that didn't get added to discord?
i have 3 commands now and non of them are getting syncing
i can only use them in debug_guild server
@slate swan
oh thats the issue, when you have a debug_guild set commands get synced in them specifically, remove that kwarg from Bot class
import discord
token = ""
intents = discord.Intents.default()
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f"Bot logged in as {client.user}")
@client.event
async def on_message(msg):
if msg.author != client.user:
if msg.content.lower().startswith("!hi"):
await msg.channel.send(f"Hi, {msg.author.display_name}")
client.run(token)
for some reason the bot doesn't say anything back
!d discord.Intents.message_content - you have to enable this intent
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
• The message was sent by the client
• The message was sent in direct messages
• The message mentions the client
This applies to the following events...
You need to await aiohttp.request
It'd be better if you extracted things into their own variables
res = await aiohttp.request(...)
content = res.content
# use content here
is this an intriguing opening message for someone who uses my game bot for the first time 
yeah, i would suggest some discord formatting to make it look a little bit more "made" and not just plain text
that's what i was i feeling, but not sure what to do
maybe shove a image of a walkie talkie in the corner as an icon but idk how to "break up" the text some more
looks like someone is really enjoying the bot
so, a lot of my functions are like this:
try:
pass
except discord.Forbidden:
pass
except discord.HTTPException:
pass
```is there a way to use a decorator to have a write once, use everywhere kinda thing?
If you are going to pass all errors, why target specific ones? Just use something like this:
try:
#your code
except:
pass
Even then, is there a way to automatically wrap a function in a try except with a decorator?
so uh
is there a way to display this error to the user
context:
@commands.hybrid_command(name="mute", aliases=["timeout"])
@commands.has_permissions(moderate_members=True)
async def mute(self, ctx: commands.Context, user: discord.Member, time: str):
use an error handler
https://stackoverflow.com/questions/66374121/discord-py-error-handling-with-on-command-error should help.
I need help with the error handling in discord.py. I want to send the server owner a private message if my bot doesn't have enough rights for a command or if my bots fail something (reason not enough
!code
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.
I have to do that for every cpmmand?
no, you can have a global error handler
^^
I advise you use error handlers for specific functions (like kick, ban, timeout etc)
Global handlers get passed the command object through context
I prefer checking the signature there if I want to handle them seperately
Less registering callbacks, not really a difference but less messy
Hi, any idea of why would I get this error:
object has no attribute 'flatten'
I have numpy imported, I learnt python a long time ago and as I remember flatten() is in numpy
The actual line looks like this:
users = await new_message.reactions[0].users().flatten()
flatten method has been removed and replaced with async iterators
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
ooooh I see, I'm not really knowledgeable in iterators, how could I replace it?
there's an example in the docs
You can flatten it with an async list comp
Thanks, I'll look into it
code = discord.ui.TextInput(label="Enter The Code", placeholder="Enter The Code Given To You!")
async def on_submit(self, interaction: discord.Interaction):
code2 = self.code.value
with open("collabs.csv", newline="") as csvfile:
reader = csv.reader(csvfile, delimiter=" ", quotechar="|")
for row in reader:
if row[1] == code2:
await interaction.response.send_message("Your code is correct, adding you to the channel!", ephemeral=True)
channel = f"🤝| {row[0]} | {row[2]}"
await channel.set_permissions(interaction.user, view_channel = True, read_message_history = True, send_messages=True, add_reactions = True)
else:
await interaction.response.send_message("Your code is either wrong or your to late :(", ephemeral=True)
class HisModal(discord.ui.Modal, title="New Collab Form"):
project_name = discord.ui.TextInput(label="Project Name", placeholder="What is the name of the project?")
secret_code = discord.ui.TextInput(label="Secret Code", placeholder="For Ex. 50 WL for Okay Bears --> okaybears50")
spots = discord.ui.TextInput(label = "WL Spots", placeholder="How many WL spots are we giving them?")
async def on_submit(self, interaction: discord.Interaction):
collab_category = bot.get_channel(1027715302986878996)
collab = await collab_category.create_text_channel(f"🤝| {self.project_name} | {self.spots}")
with open('collabs.csv', 'a', newline='\n') as csvfile:
writer = csv.writer(csvfile, delimiter=" ", quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writerow([self.project_name.value, self.secret_code.value, self.spots.value, ])
await interaction.response.send_message("Succesful Newcollab!", ephemeral=True)```
await channel.set_permissions(interaction.user, view_channel = True, read_message_history = True, send_messages=True, add_reactions = True)
AttributeError: 'str' object has no attribute 'set_permissions'
The channel object is a string and not actually a channel object
I don't have time to read your code though
Oh nvm I see it
can you give an example of a channel object please
It's an f string in your code
Am I supposed to additionally import anything? I'm using the example line:
users = [user async for user in reaction.users()]
I get the error:
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: NameError: name 'reaction' is not defined
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, DM channels are not resolved since there is no data to complete them. These are PartialMessageable instead.
You can access channel from the interaction directly
That's unrelated to that snippet
It just doesn't exist at that code point
i want a staff member (hismodal class) to create a channel with the modal and the info to be saved in a csv file, and a normal user (mymodal class) can then enter a code given by a staff member and if guesses the code right then he gets permission to that channel
I can't do all that for you. If you have specific issues I can help
Like I said before, your channel object is just a regular string
You can access the actual object using the property of Interaction
no i don't mean do all i just wanted to explain what i am trying to do sorry if it came over like that english is not my natural language
No you're good don't worry
i tried with a id and it didn't work either
You don't need to fetch the channel using an ID in this case
You can use the interaction object you receive through the callback which sets the channel property for you
How would I need to declare reactions? users exists, and I've looked at several example codes and those only had users declared as well.
Let's look back to your previous code
You're not setting a specific variable for a reaction
You're accessing the list via the message object
i have multiple "secret codes" and i don't think that that will work
Oh I think I get it, can I ask here for any further help though if needed?
Of course
i think you can just do interaction.user if i am not wrong
@commands.slash_command(name = 'verify', description="Пройти верефикацию. \n Пример: /verify")
async def __verified__(self, interaction: discord.Interaction):
if interaction.id == 559118900751761418:
embed = discord.Embed(description = '...', colour=0xF1C40F)
await interaction.response.send_message(embed=embed)
return
view = MyView(interaction)
embed = discord.Embed(description= f'**...**', colour=0xF1C40F)
await interaction.response.send_message(embed=embed, view=view, delete_after=60)
view = await view.wait()
how to make a check so that if the author of the team has a role , then he cannot prescribe a command ??
how would i do that?
you register a new event/listener called on_command_error
how to make a check so that if the author of the command has a role , then he cannot use the command ??
check interaction.user.roles
np
@commands.Cog.listener()
async def on_command_error(self, ctx: commands.Context, e: commands.CommandError):
await ctx.send("An unexpected error occurred!")
```like this?
sure
don't do what you are doing rn tho
make sure to raise unhandled error so you get to know what the reason behind error wss
bruh
for some reason
the handler in this cog also handles errors coming from other cogs
because it's a global error handler. If you want a cog-specific error handler, override cog_command_error
await cog_command_error(ctx, error)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called whenever an error is dispatched inside this cog.
This is similar to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") except only applying to the commands inside this cog.
This **must** be a coroutine.
seems nice
@commands.Cog.listener()
async def cog_command_error(self, ctx: commands.Context, e: commands.CommandError):
await ctx.reply("An unexpected fun error occurred!", ephemeral=True)
oh no
I don't think so
it's not a listener, it's a cog method that you override. Remove the commands.Cog.listener
its not an event, its a normal method
oh bruh
so technically speaking can you not load another extension with a bunch of different global handlers for things like missing perms
or would you have to redirect the cog error to that
you can have a bunch of cogs that have listeners pointing to on_command_error
that's the beauty of listeners :p
you can do that, or override on_command_error in your bot subclass
also, don't sync in setup_hook/on_ready. It can rate limit you quite quickly
can somone log into my Discord dev portal using my bot token
no
can they do anyting with it?
they can do stuff with your bot (log in to your bot and bring havoc (probably))
where do i do it then?
im giving my dc bot to somone else so they can host is
is there any way to somnehow lock a file in wich token will be stored
how to make a check so that the command can be used only in one chat ??
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
exactly what u need
Can somebody give me some code for a simple discord bot with a function of your choice?
@slate swan is there something more understandable?
how to make a check so that the command can be used only in one chat ??
sure
https://github.com/Rapptz/discord.py/tree/master/examples
I have given you about 30 here, take your pick
You need to convert the response object into a JSON first
Use await response.json()
@sick birch how to make a check so that the command can be used only in one chat ??
Then you can subscript the resultant dict
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
@north escarp ^^^
@in_any_channel(728343273562701984)
you just need to add this to the team and that 's it ?
no it's a custom check
You need to create the predicate first
You can also modify the predicate a little bit so it only accepts one ID
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)```
stop it needs to be written in a separate class from the commands or what ?
it doesn't need to be in a class
it can even be top level if needed
hey uh, if i don't do it here, then where should i do it?
how do i take in a discord channel as an argument
@bot.command()
async def my_command(ctx: commands.Context, channel: discord.TextChannel) -> None:
# channel is a discord.TextChannel instance
You can mention the channel or provide it's ID
A typehint of discord.TextChannel would only try to convert text channels, other types will error
If you want to consider the other types you can use the typing.Union[]
No, only typehint the ones your command should work on
E.g if your command sends a message to another channel, a text channel would be appropriate
If your command joins the bot into a VC, a VoiceChannel typehint would be appropriate
A text channel would be most appropriate. Consider if you want to lockdown other channels, like forums, stage channels, or even voice channels
If you're on that version feel free to use it
I just mentioned the union because I know not everyone is on that version
make a message command that syncs slash commands
that seems kinda hacky?
nope it's what everyone in the discord.py server recommends
How is it hacky?
i mean i should implement a check for if the user is a dev, right?
Yes
so a if ctx.author.id is in [asdf]?
No is, just x in y
yeah had a lapse
so i grouped TextChannel & ForumChannel & got this:
TypeError: Union type of channels must be entirely made up of channels
can you show your code?
full traceback here
@commands.hybrid_command("lockdown")
@commands.has_permissions(manage_channels=True)
async def lockdown(
self, ctx: commands.Context,
channel: discord.TextChannel | discord.ForumChannel = None, time: str = None
):
How would I get my bot to accept input from a user?
Cause I know how to accept input from the command line but idk how to do it from discord.
try using Union instead of |
same error 😦
Alright so I'm making a discord bot for the first time in quite a while, and I'm already stuck
client = commands.Bot(command_prefix= [">"])```
This is giving me an error while I'm trying to create the bot
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
command_prefix should be a string or a callable, not a list
🤔 what version are you on?
just ran pip upgrade, now it's 2.0.0
TypeError: __init__() missing 1 required keyword-only argument: 'intents'
you gotta pass in intents too
elaborate please, I didn't used to have to do that and have no clue what that means
i keep getting a indentationerror on if msg.author != client.user: if msg.lower().startswith("?hi"): await msg.channel.send(f"Hello, {msg.author.display_name}") anyone know why?
what's the full traceback?
!intent
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default discord.py has all intents enabled except for Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
you should be able to solve indentation errors by yourself, it's basic python
if msg.lower().startswith("?hi"):
^
IndentationError: expected an indented block
[Finished in 187ms with exit code 1]
[cmd: ['python3', '-u', '/home/_sakai/learning/discord_bot.py']]
[dir: /home/_sakai/learning]
[path: /usr/local/sbin:/usr/local/bin:/usr/local/games:/usr/sbin:/usr/bin:/usr/games:/sbin:/bin]```
maybe indent everything w/ 4 spaces instead?
I must be an idiot I don’t understand how to implement it. It keeps saying that discord doesn’t have ext.
show code
Do you have any files or folders named "discord"?
I do not.
How do I mention a role?
I have a command that uses a role as one of its parameters, pyasync def tag(ctx, amount, role:discord.Role, *, message = ""):
and I can't figure out how to mention the role
is it possible like this?
role.mention?
where did you put it?
@client.command()
async def tag(ctx, amount, role:discord.Role, *, message = ""):
if await check_lock():
return False
try:
amount = int(amount)
except ValueError:
await ctx.send("<amount> Must be a full number", delete_after=15)
for i in range(amount):
await ctx.send(f"{role}{message}")```
I also tried using an f""
but that didnt work
why are you using .format like that?
I was just trying something else
you can just
await ctx.send(f”{role.mention} {message}”)
my b on mobile can’t really format properly
i think there’s a different issue then, mind taking a screenshot so i can see the layout?
for your try and except you can just take in amount as an int
amount : int
as for the mention unless you already tried {role.mention} i’m not exactly sure what the issue is
Yeah I have tried the role.mention
i have no clue whats wrong with it
anyways thanks man
ahh yeah didn’t consider that
im having issue on makin a dsc bot bot and i cnt identity the error all it says is Traceback (most recent call last):
File "main.py", line 74, in <module>
bot.run("TOKEN") and sum html and css
but thrs nothing wrong in code
client.run should work shouldnt it?
Are u on replit?
i could try switchin to client but i always get rate lim
yes
can i inv u to code to see error
can u try using another ide
It means u got ratelimtied, not ur fault tho. Side affect of replit
ok ill kill 1
that happens to me in replit too
you need to set the secret or whatever since your using replit
im pretty sure
i alr did
lemme see
Hey @rich oxide!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
lol
Omg ill send in yalls dms
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
I fixed @maiden fable
@maiden fable oi mate, is there any way to obfuscate code without pyarmor? like any alternative?
:incoming_envelope: :ok_hand: applied mute to @slate swan until <t:1665378965:f> (10 minutes) (reason: mentions rule: sent 8 mentions in 10s).
The <@&831776746206265384> have been alerted for review.
cause with pyarmor im getting this error continuosly:-
https://paste.nextcord.dev/?id=1665377768450150
whereas in a src code everything seems to work fine
here is one.
https://liftoff.github.io/pyminifier/
I'll check ty
Well, you can use nuitka to compile it to C code, or use Cython. But tbh, if u wanna obfuscate, either use pyarmor and kind or convert it to C
The question is more suited for #c-extensions imho
why obfuscate a discord bot tho just curious
ah okey
nah its just i wanna check some things but it isn't working
True that’s kinda weird
!unittest
How can I make an argument be a true or false statement? For a slash command
@client.event
async def on_ready():
print("Bot is up.")
I used to run this at the beginning of my bot to notify me when the bot is up. I don't know what changed, but it doesn't work anymore.
It doesn't raise an error, it just doesn't work.
Did you migrate to 2.0?
yes
The token area got changed. It uses asyncio.run() now
ps i reccomend @bot.event
Whats the difference
Client it easyier to get rate limited
Bot your less likely
That's not how it works
discord.Client and commands.Bot are the same, just that commands.Bot has support for making commands easily
Do you know how to use database?
example?
can someone explain how cooldown in hybrid commands work or refer me to their docs
nothing like that is important
mind showing full code?
you need to use the commands.cooldown decorator
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
Is there an alternative of Bot.get_context for inter class? (disnake)
don't think so, you get context from message class, but interaction is a discord class in itself
if i use this i get an application not respond error
yes because you need to send a response for the interaction even if its on cooldown
make an error handler
if i add a interaction argument it just says this
wait give me 1 minute
The application did not respond
@whitelist.error
async def on_whitelist_error(self, interaction:discord.Interaction, error):
if isinstance(interaction,error,commands.CommandOnCooldown):
await interaction.response.send_message(f"Command is on cooldown, you can use it after {round(error.retry_after, 2)} seconds.",ephemeral=True)
``` something like this? @slate swan
why would it be an interaction in a hybrid command
you get context for hybrid commands
but it will throw applicaiton not responding if i throw Context as an argument
@slate swan
no it wont. use ctx.send to create a response inside the error event
wait then
@whitelist.error
async def on_whitelist_error(self, ctx:Context, error):
if isinstance(ctx,error,commands.CommandOnCooldown):
await ctx.send(f"Command is on cooldown, you can use it after {round(error.retry_after, 2)} seconds.")
your isinstance statement is faulty
what should it be then?
if isinstance(error, commands.CommandOnCooldown) ...
wait
it works now thanks man!
no
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
How would I get this to store what the user said?
Because I plan on storing the trigger and using regex to isolate the number after the +.
Then incorporate it into the final calculation to return the number with the modifier applied.
what do you mean "store what the user said?"
Like make it a variable.
So I can put what they said into a variable.
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
I'm assuming you're looking for this
Not really since that’s an additional reply from the user I want it to be able to take one prompt and be able to use it from there.
Cause rn the biggest issue is the variable modifiers.
anyone know how i can have on_message and commands work at the same time
course you can, you just need to add a single line at the end of the on_message to process it as a command
await bot.process_commands(message)
or alternatively use a listener
allows you to easily partition your bot into multiple parts and load/unload them as required
also helps you NOT have a 50k line file as your bot grows and new features are introduced
the so called "modularity" of discord bots
also groups into categories which can be seen from the help cmd
is this cog loaded
yeah
Do you have the members intent
what is member.user supposed to be
yeah
Can you show me
Show intents
doesn't members come in default
No
^ this also doesn't exist
str(member) returns the full username + discrim though fyi
ty
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
how can I add an error message here ?
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)```
if statement, if ctx.channel.id in channels, use else for the error. If channels is an list, you may have to iterate through it. not 100% sure
if ctx.channel.id in channels:
embed = discord.Embed(description = 'Вы уже прошли верефикацию', colour=0xF1C40F)
await ctx.send_message(embed=embed)```
is that what you need ?
def in_any_channel(*channels):
async def predicate(ctx: Context):
if ctx.channel.id in channels:
return ctx.channel.id in channels
else:
## error here ##
return check(predicate)
and that is, write the message after else ?
Error there
Do people learn coding discord bots just as a hobby?
@still elbow thanks for the help
most of us sure, some use it to learn, others might be paid
If someone steals my bots token can they : a)harm my account (log into my account b)log into discord developer portal
If someone gets your bot token, they can control your bot. You can regenerate your bot token in the dev portal if it has been leaked.
file = File(fp=background.image_bytes, filename="wlcbg.jpg")
welcome_embed = discord.Embed(description=f"Hii {member.mention}! Welcome To **{member.guild.name}**")
welcome_embed.set_image(url="attachment://wlcbg.jpg")```
how can i set local image in my embed?
right now i can only see the description of embed
and i get no error and the image doesnt show up
should be discord.File
and make sure you are providing the correct path
Building it from ground up with JSON was probably not a good idea then, eh?
It's just None, not None()
None, True and False are all singleton unpolymorphic instances that cant be called!
is it possible to run multiple bots with the same project ?.
sure but why
i want to run 3 of my bots with the same project , to use them at the same time
can you learn me how to do it ?
You can run them at once but I don't see why it has to be in the same project
Why can't you run 3 different processes
Run them as seperate processes in different project directories
Much easier than trying to fiddle around with threading or multiprocessing
i know but my objectif is to run them in one project 🙂😃
Right, but why?
Objective doesn't come out of nowehere
easier to run , a single activity ...
^
It's not really easier to run, harder to create, and you won't have a single "activity"
Activity is android term
What would be easier to run is to have each of your bots in their own container, then run docker-compose up and start up all 3 bots at once
bro why you don't want to tell me how to do it 🙂
Because it's not worth the effort, I'm just trying to save you some headache
but i want to learn it 😃
Learn docker?
Docker is probably better to learn than threading IMO
One of the most widely used DevOps tools
._.*
Threading is important too ofc but not for this case
I can see why you want to learn it, threading and multiprocessing are both important, but they're not always used, and only used in certain cases. This is not one of those cases, you don't need threading here. If you do want to learn about it, RealPython has a good article you can use to learn threading: https://realpython.com/intro-to-python-threading/
You want to run 3 different bots (different tokens) or 3 instances of the same bot?
3 different bots 😃
Either way it comes down to the same thing
Run multiple processes yeah
It's usually easier to learn something when applied to a project that could benifit from said concept
With one bot it's a bit more complicated and only needed if you're hitting cpu limit
When you try to apply something to a project that does not benefit, it just makes it harder to learn
Sadly my docker guide PR hasn't gotten merged yet
😳
Thanks for the reminder
I can link a bit of outdated version tho it doesn't differ that much
