#discord-bots
1 messages · Page 169 of 1
more quality is not more delay
But sending an edited image shouldn't give delay
Saving image takes time but not sending
how slow are we talking?
3s
because if its slow to just respond
No need to use another method separate
so i was thinking it just the quality
Nope...
the elements of image u know
prob ur internet tbh
i literally did two images the same format same size but the delay time is different
i tried many images
Editing image in good quality on code it takes time to save but while sending saved image through discord , there is no way it takes delay
Unless this
it is saved image
especially if u just using a saved img from a directory
hmm imma try hosting my bot from replit and i will be back
last try
that is even worse lmfao
Ye
better than my wifi
That's true too 🗿
just wanna check , not like iam gonna host my bot on replit 24/7
ahh like
async def method(url):
async with .......as session:
response = ........get(url)
Kinda like dat
It's separate method
hey I need help I'm trying to make it where once you do *end and the paragraph of your advertisement but it does not work once it logged plz help
thats normal
....
?
Man's trying to earn from discord bots
Imagine if I would do that stuff
Anyway what the problem is there
how could I make it so that after running a certain command and the user types chunks of text how can I make it where the bot logs the chunks of text that the user writes? this is my problem and I tried doing that
bobux scams
😏
Actually we could probably integrate purchases to bobux after we make site just to try
Maybe will be enough to cover VPS costs
anyone gonna help me ?
Logs where? Types where?
*end {chunks of writing} log = self.bot.get_channel(1058528243289968670)
Scam hm
Yeah /slots go brrr
Make it on discord 😏
BadModal for card info
:yes:
I dont know but when a good alternative is using ID's for the ads you want to accept/deny
Store the ID and message info in a database
Someone can then do ?deny ID and it would deny the ad
idk if i explained that well
Bobux bot codebase names be like
utils.utils.check_if_stupid
utils.views.BadModal
res/user_insults.json
All messages have IDs
So why even store that
What are they trying to achieve? Application reviews or smth
Yeah
think so
Okay but I'm trying to make it where the bot could log chunks of text if the user writes paragraphs about his advertisement
Just attach a persistent view with deny/approve buttons, you can access the message via message interaction
yeah but it is very hard to do
I alright linked you the link in docs explaining that
I usually do prefix commands not slash commands
Yeah It didn't help either
i dont really understand what you mean
sorry im kinda thick
What did you do
let me show you an example
Lmao maybe you meant sick?
*end (user's large writing)
Cause thick is like uh fat?
how can i get message id of the message the bot sent
like on using a command bot replied with a message, how can i get that messages id or that message itself
Yes and what you didn't understand from example
I read this part
async def func(ctx, *, large_text)```
no it also basically means dumb
Bro you were supposed to look at the example, not scroll or anything
you need to fetch it
@slate swan anyway
wait
You mean "get message user replied to" or what
message.reference.resolved
get message the bot sent as a reply
well i wanna make suggestions command
the bot will send a message and will react to it with emojis
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") to do this.
Examples
Usage...
ok so, i want message id of this message
🗿
🗿
So exenifix i am getting my beta bobux's $$?
You shouldn't be making sessions on each call of the method, use a single session. Why are you converting self.user_id to a string in an f string?
.
what?
it is suggested you use a single session for the lifetime of your application to benefit from connection pooling
You're missing my point? You shouldnt be using requests either?
!d asyncio.create_task
asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") for the *coro* to run in. The current context copy is created when no *context* is provided.
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
Note
[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task "asyncio.TaskGroup.create_task") is a newer alternative that allows for convenient waiting for a group of related tasks.
!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.
it can be, but lets not talk about that
Its an esoteric way, you should just use create_task or use a classmethod, but to avoid any other issues i would recommend using the latter
that's why it was italicized
Ping or message me if you would be able to test the multiplayer game i made in discord.py
``Traceback (most recent call last):
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Nick\PycharmProjects\dis bot\test bot.py", line 37, in <module>
client.run("TOKEN")
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\client.py", line 580, in login
data = await self.http.static_login(token)
File "C:\Users\Nick\PycharmProjects\venv\lib\site-packages\discord\http.py", line 805, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x00000224C55315E0>
Traceback (most recent call last):
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Nick\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed``
Why am I getting this error
I'm sure I have the right token
And the bot has admin perms
did you make sure the file was saved? your traceback would suggest the token passed to run() was "TOKEN"
Yeah I even tried making a new bot and different code but says the same thing
so that means you edited your traceback to hide the token, right?
did you copy it from the Bot page of your application in the dev portal site?
Yeah
I'm not sure I'm only just learning python but I'm using pycharm so I just rerun to save or isn't that what u mean
@hushed galleon so what now
i have no idea what your original question is
saving the file is different from running the file, but i think pycharm autosaves on run anyway
Yeah
Also it happened on its own , im using the same code that I used before while it was still working
Hello I bought a VPS on racknerd someone knows and can help me in uploading my files?
I have a main.py, requirements.txt and a data_mysql.sql
creating a single ClientSession outside of your update_values() isn't needed, its an optimization as noid described which helps when making lots of requests to the same servers
also i dont know what check method you're referring to, nor do i know the purpose of polling updated loot information in the first place
but why are you trying to poll this information? is it for real-time updates?
Where can I upload my files ?
ik file Zilla but idk where can I get my sttp
ah whatever in that code you commented out the request, so what was wrong with it before?
and also idk where upload them
well they didnt say to stop making requests entirely, just store the session somewhere
e.g. ```py
bot = commands.Bot(...)
async def main():
# Create a single session here
async with bot, aiohttp.ClientSession() as session:
bot.session = session
await bot.start(...)
class User:
def init(self, bot):
self.bot = bot
async def update_values(self):
async with self.bot.session.get("api-link") as response:
... # retrieve the values and do your calculations like before
users = [User(bot), ...]
asyncio.run(main())```
what? no, only the session is stored, you're still making a new request each time you update
Session encapsulates a connection pool (connector instance) and supports keepalives by default. Unless you are connecting to a large, unknown number of different servers over the lifetime of your application, it is suggested you use a single session for the lifetime of your application to benefit from connection pooling.
its just different variable names, do whatever you want with them
whatever users you have in your loot_table
well you need access to the session in your update_values() method somehow
you can pass just the session instead of the entire bot, or get hacky and reference the bot as a global variable
judging from https://blog.racknerd.com/a-list-of-useful-linux-commands-linux-command-cheat-sheet/, they just expect you to upload files over ssh using the scp/sftp protocol on the IP address given to you
well given that you're referencing client as a global variable already, you can just write client.session to access it
also worth noting that if you werent using a main() function before, you'll need to manually call discord.utils.setup_logging() since that's one of the things client.run() would have done
Why upload files via SFTP when you can upload them to github and then clone on VPS
Or even use workflow for automation
which is the best for hosting a discord bot?
I do not know how to do
Just take latest version of ubuntu, doesn't really matter
I meant latest LTS which is 22.04.1 iirc
There were weird ssh bugs in 22.11 when I tried it last time, had to rollback
You don't know how to use git generally or how to clone on VPS
Knowing git is an important skill, I suggest looking up tutorials
yes but its possible to upload with file Zilla right?
Yeah
I would recommend termius app cause it has both sftp client and ssh + nicer interface than firezilla's
Have been using it since got my first VPS
what?
terminus app is for uploading files?
Termius helps to organize the work of multiple DevOps and engineering teams. It reduces the admin work for managing users. Enterprise compliance. SOC2 II report.
never used it
There's "SFTP" tab, iirc it was available only to pro subscribers (you could just create account with new email to get infinite free trial) but now it's free
@slate swan what’re you trying to do?
trying to host my discord bot on racknerd
it's a vps
Aye, trying to get my bot to read a list from a json in the directory, but its saying it cant find it?
from discord.ext import commands
from TOKEN import token
import asyncio
import os
intents = Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!',intents=intents)
@client.event
async def on_ready():
print("RijalBot online")
async def load():
for file in os.listdir('./commands'):
if file.endswith('.py'):
await client.load_extension(f'commands.{file[:-3]}')
async def main():
await load()
await client.start(token)
asyncio.run(main())```
**cmds.py** [cog/extension]
```import discord
from discord.ext import commands
import json
file = json.load(open('narrators.json'))
narrators = file.get('narrators')
class cmds(commands.Cog):
def __init__(self, client):
self.bot = client
@commands.Cog.listener()
async def on_ready(self):
print("CMD Cog working")
# RIJAL COMMANDS BEGIN HERE:
@commands.command()
async def rijal(self,ctx, message:str):
if message in narrators:
await ctx.send("e")
# RIJAL COMMANDS END HERE
async def setup(client):
await client.add_cog(cmds(client))```
heres my directory
Path should be rijaldata/narrators.json
Almost
Hey any idea how to create those "forms" looking window, documentation or how they are called?
Except you better subclass Bot and set the session as its attribute
Cause you need to overwrite __init__, setup_hook and close methods
These are called modals
Thanks!
@oblique sorrel set the session attribute in __init__ and overwrite this
async def close(self):
await self.session.close()
await super().close()```
Yeah right, I am coding a bot to run applications for a Minecraft event I host and thaught those could be cool to use
It's named session why would it be request
In overwritten MyClient.close()
Unrelated
Is it still that ChatGPT thing
!d discord.Client.run
run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.
If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").
This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.
Warning
This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
Ok see in your subclass you add this to __init__ (doesn't matter where exactly in it at all)
self.session = aiohttp.ClientSession()```
Then you make a method for your subclass (cause it exists in superclass, it's called *overwrite*)
```py
async def close(self):
await self.session.close()
await super().close()```
Running would look like
```py
# some init stuff whatever
client.run(token)```
I think session closing is async but I don't remember
!d aiohttp.ClientSession.close
coroutine close()```
Close underlying connector.
Release all acquired resources.
Yeah it's coro
Why await
Eh wait
That's very weird cause I used it in a similar way and got no deprecation warnings
Maybe I've confused something
No wait
What version of aiohttp you have
What exactly
Is it 3.8.3 or another
pip freeze
Interesting
Ok send the whole code please
Aye, im not familiar with JSON, so i have a dict, and if my message has a word which is any of those keys, it should print the value,
but in the JSON file, the dict has no name, so how will I call it?
#DICT
narrators = {
("e"): "a"
}
with open('narrators.json', 'w') as f:
json.dump(narrators, f)``
**narrators.json**```
```{"e": "a"}```
**cmds.py** [cog]
```import discord
from discord.ext import commands
import json
file = json.load(open('narrators.json'))
narrators = file.get('narrators')
class cmds(commands.Cog):
def __init__(self, client):
self.bot = client
@commands.Cog.listener()
async def on_ready(self):
print("CMD Cog working")
# RIJAL COMMANDS BEGIN HERE:
@commands.command()
async def rijal(self,ctx, message:str):
if message in narrators.keys():
await ctx.send("e")
# RIJAL COMMANDS END HERE
async def setup(client):
await client.add_cog(cmds(client))```
**main.py**
```from discord import Intents
from discord.ext import commands
from TOKEN import token
import asyncio
import os
intents = Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='!',intents=intents)
@client.event
async def on_ready():
print("RijalBot online")
async def load():
for file in os.listdir('./commands'):
if file.endswith('.py'):
await client.load_extension(f'commands.{file[:-3]}')
async def main():
await load()
await client.start(token)
asyncio.run(main())```
Im trying to get it so if I send a message, it checks if the message is a key in the json dict, so I did !rijal e, but I got nothing, not even a traceback
So is there any way to fix it
Can someone help
Think I figured it out
how to get info from discord.ui.TextInput?
Hey, how do I make it where after the program picked a random place to work at and a random paycheck how do I log that? (discord bots experts)
!d discord.ui.TextInput.value
property value```
The value of the text input.
Huh
I'm making a banking system
and I'm trying to add there balance and etc
Just pick random item then store it in a variable
!e
import random
meows = ("meow", "mau")
item = random.choice(meows)
print(item)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
meow
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside of them.
By default your code is run on Python's 3.11 beta release, to assist with testing. If you run into issues related to this Python version, you can request the bot to use Python 3.10 by specifying the python_version arg and setting it to 3.10.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e 3.10 ```py @commands.command()
@commands.Cooldown(1, 20, commands.BucketType.user)
async def work(self, ctx):
place = ["Mc Donalds",
"Burger King",
"Checkers",
"Zembay PD",
"Zembay FD",
"Zembay DOT",
"Zembay National News Station"
]
Money = [ 150,
130,
400,
900,
1000,
40,
1,
60,
30,
20,
950,
12,
32,
43,
12,
]
Balance = random.choice(Money, place)
await ctx.author.send(f"You worked at {random.choice(place)}, and you got {random.choice(Money)}")```
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | File "<string>", line 2
002 | @commands.Cooldown(1, 20, commands.BucketType.user)
003 | IndentationError: unexpected indent
when I did that it picks randomly in the data base too
What
nice data base 
It's just
mn = random.choice(Money)
rt = random.choice(place)
await ctx.send(f"You got {mn} from working at {rt}")
# do anything with it
And how do I store it in another function?
is it safe to run a discord bot on replit
It’s not recommended
See the discord bot hosting thread for more details on that.
I've heard that you can get a year free at aws if you link a credit card
a year yeah
but all permantly "free hosts" always have something not good about them
for example replit has the ratelimiting stuff
hey, ive got a problem
what
@bot.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, limit: int):
await ctx.message.delete()
await asyncio.sleep(1)
await ctx.channel.purge(limit=limit)
await asyncio.sleep(1)
purge_embed = discord.Embed(title='Purge [!purge]', description=f'Successfully purged {limit} messages. \n Command executed by {ctx.author}.', color=discord.Colour.random())
purge_embed.set_footer(text=str(datetime.datetime.now()))
await ctx.channel.send(embed=purge_embed, delete_after=True)```
it purges the messages with the int i set, but it doesn't send the embed after purging
remove delete_after and then try it to tst
yep, works now, thanks
Is it possible to edit a bots previously sent message by using the message id? And if so, could I get an example of how it would look like?
You would use TextChannel.fetch_message to get the Message via it's id and then use it's edit method
But are you trying to edit a very specific message?
import discord
from discord.ext import commands
from discord.ext.commands import has_permissions, MissingPermissions
import asyncio
import datetime
intents = discord.Intents.all()
from discord import app_commands
help_command = commands.DefaultHelpCommand(
no_category = 'Commands'
)
client = discord.Client(intents=intents, description = 'Welcome to Nucleus! The multifunctional discord bot made by Technoglave', help_command = help_command)
tree = app_commands.CommandTree(client)
member = discord.Member
@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=1056934892392419329))
await client.change_presence(activity=discord.Game(',help ┃ Created by Technoglave'))
print(f'{client.user.name} has connected to Discord!')
@tree.command(name = "ping", description = "ping command", guild=discord.Object(id=1056934892392419329))
async def ping(interaction: discord.Interaction):
await interaction.response.send_message("Pong!")
@tree.command(name='commands', description='List commands', guild=discord.Object(id=1056934892392419329))
async def listcommands(interaction: discord.Interaction):
await interaction.response.send_message(f"For Fun commands: ,fun;\nFor server info: ,info")
@tree.command(name='warn', description='Warn a user', guild=discord.Object(id=1056934892392419329))
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member, reason=None):
await interaction.response.send_message(f"{member.mention} was warned for {reason}")
code shows this error:
you need to do reason: str = None instead of reason=None
Nope, just trying to edit any message sent by the bot with said message id
I see
You'll need the channel ID too
get the channel with bot.get_channel --> fetch the message with channel.fetch_message --> edit it with message.edit
there's also PartialMessage if you want to avoid making the extra API call to fetch the message py channel = client.get_partial_messageable(1234) message = channel.get_partial_message(5678) await message.edit(...)
How do I unban every user in the ban list of discord? I was thinking of using a for loop with ctx.guild.members but that wont get the guild bans.
!d discord.Guild.bans
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
And then I can do entry.unban() or would it be entry.user.unban()?
guild.unban(entry.user)
thank you very much!
how to like generate nested objects in json ? for an inventory.
Ooo wish I new this earlier
data = {}
data[str(user_id)] = {}
data[str(user_id)]["consumables"] = ...
easy as that
ama try that .
how do I edit the status of a bot?
image = random.choices(imagesz, weights=(70, 70, 60, 50, 50, 50, 10), k=1)
with open('inventory.json', 'r') as f:
data = json.load(f)
data = {}
data[str(ctx.author.id)] = {}
data[str(ctx.author.id)]["consumables"] = images[0]
with open("inventory.json", "w") as f:
json.dump(data, f, indent=4)
why does json make images[0] "/"
oh the variables are different..
;-;
@tasks.loop(seconds=3)
async def change_status():
await client.change_presence(activity=nextcord.Game("your status"))
@client.event
async def on_ready():
change_status.start()
print("online!")
🥄
& don't use on_ready for anything. setup_hook exists
on_ready can be called multiple times, while setup_hook doesn't.
hmm
it overwrites the data of an user, is there any way to make new lines with these
Just for reference
https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.Bot.setup_hook ("This is only called once, in login(), and will be called before any events are dispatched, making it a better solution than doing such setup in the on_ready() event.")
it works like an event?
In general
Yep
wdym?
basically i wanted to make an user inventory not just a inventoruy
now when i do this it overwrites
the inventory of an user
how do i fix this
data[str(user_id)] = {} this line sets it to a blank dictionary
hmm
so if i remove the = {} it will work?
I don't understand why you're setting data = {} after loading it from the json either
i think for a parent object
if i dont do that
data = json.load(f)
data = {}
``` same thing is happening here.
i remove it
so str(user_id) isn't in the dict
so you should add it to the dict only if isn't there already
heH?
you add str(user_id) to the dictionary
yuh?
if it is not in the dictionary
then key error?
if it is already in the dictionary and you set it to {}, then you're overwriting it
wiat so i removed the ```py
data = {}
now what is the value of data
Dictionary 📕
data = json.load(f)
yes, so it's your json data
so if str(user_id) is in that dict, you will get the corresponding user data
if it's not, you'll get a KeyError
which is why you should ensure that str(user_id) is in the dict before trying to access it...
rf
does anyone know how to lock (not just archive) discord threads via a discord bot? ive tried searching the docs and im not havin much luck
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
Hi there, how can I get my bot's commands to show up in the / menu?
At the moment the commands work but don't appear or function as slash commands and I'm unsure how to change that.
import asyncio
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
client = commands.Bot(command_prefix='/', intents=intents)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
channel = client.get_channel(1059413596372729909)
guild = client.get_guild(1059392729286709298)
await guild.create_role(name='Support Team')
await guild.create_role(name='Muted', permissions=discord.Permissions.none())
ticket_counter = 0
@client.command()
async def ping(ctx):
await ctx.send('Pong!')
That's not how you create slash commands
There's a walkthrough in the pins
async for ... in bans(*, limit=1000, before=..., after=...)```
Retrieves an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") of the users that are banned from the guild as a [`BanEntry`](https://discordpy.readthedocs.io/en/latest/api.html#discord.BanEntry "discord.BanEntry").
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to get this information.
Changed in version 2.0: Due to a breaking change in Discord’s API, this now returns a paginated iterator instead of a list.
Examples
Usage...
Im not gettting any traceback, my command simply doesnt work?
#DICT
# THIQA AND OTHER
weak = "Weak"
thiqa = "Reliable"
unknown = "Unknown"
semi = "Some accepted."
# OTHER
narrators = {
#ABAN B. ABI AYYASH
"Abān b. Abī ʿAyyāsh": weak
}
with open('rijaldata/narrators.json', 'w') as f:
json.dump(narrators,f)```
from discord.ext import commands
import json
narrators = json.load(open(r"C:\Users\intel\Desktop\rijalbot\rijaldata\narrators.json"))
class cmds(commands.Cog):
def init(self, client):
self.bot = client
@commands.Cog.listener()
async def on_ready(self):
print("CMD Cog working")
RIJAL COMMANDS BEGIN HERE:
@commands.command()
async def rijal(self,ctx, message):
val = narrators.values()
weak = "Weak"
if narrators.keys() in message:
await ctx.send("e")
RIJAL COMMANDS END HERE
async def setup(client):
await client.add_cog(cmds(client))```
I need it to check a dictionary, if the message contains a key from the dictionary, it needs to check its value, and if its value equals something I specify, it should message something
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
If another bot, such as MEE6, were to say a certain keyword, is it possible for my bot to be able to react to it? I know that commands aren’t possible for bots, I wanted to see if it was the same for simple listens
Use on_message event
Read the error
How can you possibly get every error that shouldn't be possible to get
Ik but will another bot reply
yes
on_message picks up all messages that are visible to the bot
where did you get .fetch_premium_subscription from
The docs contains a list of attributes and methods that you can use
don't access an attribute which doesn't exist
Hey @sand falcon!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
thanks
code https://paste.pythondiscord.com/oyekakaciv
error
@bot.slash_command()
^^^^^^^^^^^^^^^^^
AttributeError: 'SlashCommand' object has no attribute 'slash_command'
ping when reply
Remove slash command import it ain't needed
When you define bot slash commands object is imported with it
As an attribute
ok also i am using pycord
i still got the same error
Ewww
after removing
Who uses pycord 💀
Menace to society
oh
it didnt work what should i do
?
hey, ive got an issue
so i have this warn embed that im looking to send to not just the slash command interaction response, but also to the dm's of the user who got warned so they know that they have been warned
but for some reason, the dm function returns this error:
discord.app_commands.errors.CommandInvokeError: Command 'warn' raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
code attached:
@tree.command(name='warn', description='Warn a user',)
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member, reason: str=None):
await interaction.response.defer(ephemeral=True)
warn_embed = discord.Embed(title='Warning', description=f'Successfully warned {member.mention} for {reason}.', color=discord.Colour.og_blurple())
warn_embed.set_footer(text=str(datetime.datetime.now()))
await interaction.followup.send(embed=warn_embed)
user=client.get_user(member)
await user.send(embed=warn_embed)
Aye, tryna get my bot to check if the message content contains any keys, when I do !rijal a, it gives me nothing
async def rijal(self, ctx):
for key in narrators.keys():
if key in narrators.keys() == ctx.message.content:
await ctx.send("e")```
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
narrators.json
{"a": "Weak"}
client.get_user
is returning None
and you don't wanna do that
since here you can simply do member.send
you need not get a User object when you already have a Member object since they both have same attributes (Member has guild related information also)
great, works, thanks
i realised that after you said it
that syntax isn't even valid ig
you need to typecast the keys to a list and use the in keyword
keys = list(narrator.keys())
if ctx.message.content in keys:
...
lol it's fine, better to understand than regret it later
lol
Can’t you just do content in narrator
keys() are already set-like so converting them to a list would be somewhat inefficient
(more specifically set-like performance for membership testing)
hm well, that too
well you could, I'm not even thinking straight 😔 my bad
Hey guys, I'm developing my first Discord bot and was curious on whether I should code it with custom commands (e.g. !kick @pulsar kettle) or use Discord's slash commands (/kick @pulsar kettle), any thoughts?
(and yes I am using discord.py)
slash commands
but if youre doing a first
actually yeah if tyoure doing a first you should do it through custom commands
since slash commands are a bit more complicated
Yeah because I coded like 7-ish custom commands then realised slash commands exist aha
I'm able to rewrite it for slash commands if needed
If you're planning on growing your bot to 100+ servers (which requires verification) then you'll need to switch to slash commands
If you are a beginner and want to do slash, use disnake, if you are a lazy person and want to do slash, use disnake, if you want text commands, use whatever (disnake), if you are a tryhard, use dpy
also on that, im looking to fetch the server's name in my code and i can't really seem to find how to do it. can anyone show?
@tree.command(name='warn', description='Warn a user',)
@commands.has_permissions(kick_members=True)
async def warn(interaction: discord.Interaction, member: discord.Member, reason: str=None):
warn_embed = discord.Embed(title='Warning', description=f'Successfully warned {member.mention} for {reason}.', color=discord.Colour.og_blurple())
warn_embed.set_footer(text=str(datetime.datetime.now()))
await interaction.response.send_message(embed=warn_embed)
warn_embed = discord.Embed(title='Warning', description=f'{member.mention}, you have been warned on {SERVER NAME HERE}.')
await member.send(embed=warn_embed)```
I tried out slash commands by rewriting my ping command and here's what I had:
async def ping(interaction: discord.Interaction):
await interaction.response.send_message('pong!', delete_after=5)```
interaction.guild.name presumably
Should I write the code so it's compatible with both custom AND slash or just not bother and only go for slash?
you could write it for both, but note that discord won't give you access to the message content intent just for the purpose of commands (when you verify your bot)
So it's better to just focus on slash commands?
Probably. It will be less limiting
Alright cool, thank you for your help guys <3
so i put {interaction.guild.name}?
nah that wont work i think
its just @tree.command
the decorator is callable
works for me
bot.tree gives a CommandTree
oh i didnt know that
its not really hard to make both slash and text commands compatible, you could just use hybridcommand, and it would use the respective methods depending on if its slash or text internally, the interface stays the same
breh
So I did what you told me, just changed a little
from discord.ext import commands
import json
with open(r"C:\Users\intel\Desktop\rijalbot\rijaldata\narrators.json") as f:
narrators = json.load(f)
class cmds(commands.Cog):
def __init__(self, client):
self.bot = client
@commands.Cog.listener()
async def on_ready(self):
print("CMD Cog working")
# RIJAL COMMANDS BEGIN HERE:
@commands.command()
async def rijal(self, ctx):
keys = narrators.keys
if ctx.content in keys:
await ctx.send("e")
# RIJAL COMMANDS END HERE
async def setup(client):
await client.add_cog(cmds(client))```
but when I do !rijal a, it still doesnt do anything
json
{"a": "Weak"}
!d dict.keys
keys()```
Return a new view of the dictionary’s keys. See the [documentation of view objects](https://docs.python.org/3/library/stdtypes.html#dict-views).
.keys is a method, so call it
what is ctx.content?
Also your check is kinda useless
Hm?
Since you're checking if the exact whole message content is in the dictionary
Ah
!e
d = {"a": 0}
print("a " in d.keys())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
If I wanted to check if a word was present in the message, i'd reverse the statement?
async def check_date():
while True:
now = datetime.datetime.now()
if now.day == 1:
await start_monthly_event()
if now.day == 1 or 15:
await start_biweekly_event()
await asyncio.sleep(86400)
what is the correct way to have the bot check for 2 different days for the biweekly event?
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!
He's sleeping using asyncio.sleep, so no exactly
Trying to implement slash commands into my Discord.py bot, the following command adds the mute role to the member and sends the embed as intended, however it doesn't remove the mute role after the time is up. Can somebody help please?
@bot.tree.command(name='tempmute', description='Temporarily mutes a member')
@has_permissions(kick_members=True)
async def tempmute(interaction: discord.Interaction, member: discord.Member, time: str=None, reason: str=None):
desctime = time
guild = interaction.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
time_convert = {"s":1, "m":60, "h":3600, "d":86400, "w":604800, "mo":18144000, "y":31536000}
tempmute= int(time[:-1]) * time_convert[time[-1]]
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False, read_message_history=True, read_messages=True)
await member.add_roles(mutedRole, reason=reason)
embed = discord.Embed(title=(f'***{member} has been muted for {desctime}*** | {reason}'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
await member.send(f"You have been temporarily muted from: ***{guild.name}*** for **{desctime}** | {reason}")
await asyncio.sleep(tempmute)
if mutedRole in member.roles:
await member.send(f"You have been unmuted from: ***{guild.name}***")
await member.remove_roles(mutedRole)
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
so it is checking for it, that's not the issue, what is happening, and sorry for not explaining enough in my question, is it thinks every day is "1" for the biweekly, so it is triggering on every day
discord.py's task loop can do that for you
In the time argument, you can give it exact time to run
!d datetime.time
class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
All arguments are optional. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
Or just make it run every day and check the day Ig 
i think that is the issue, the reloading of the bot lol
is there any way i can add an image/gif to my discord bot's activity?
no i mean as in my discord bot is playing an activity and i want to see if i can add an image to that playing activity
thanks everyone who pointed me in the right direction, it is working as intended now.
alright lmao
i am a grade below novice when it comes to python, i wish i could help ya, but i don't think i can
bad_word_count = open("bad-word.json")
in_memory_word_count = json.load(bad_word_count)
```py
def write_word_count_to_list(in_memory_word_count):
with open('bad-word.json', mode='w') as f:
json.dump(in_memory_word_count, f, indent=2, sort_keys=True)
def add_words(user):
try:
with open("bad-word.json", mode="r"):
in_memory_word_count[f'{user.name + user.discriminator}'] = int(in_memory_word_count[f'{user.name + user.discriminator}']) + 1
write_word_count_to_list(in_memory_word_count)
except KeyError:
with open("bad-word.json", mode="r"):
in_memory_word_count[f'{user.name + user.discriminator}'] = 1
write_word_count_to_list(in_memory_word_count)
def check_words(user):
with open("bad-word.json", "r") as total_words:
total_words_data=json.load(total_words)
return total_words_data
this is how i updated a json file in my last discord bot
yeah, i don't know what im doing
i am literally having chat gpt explain things to me in steps, and sometimes have to have them explain it to me as if i were 5
ChatGPT doesn't know everything and it can give incorrect information
i don't like the way it codes most of the time, but it usually gives me something i can work with haha
my favorite thing about chat gpt is the lists it can make me for json files, i am building an art themed discord channel, so character generators are fun, and in the past i had to think of all the words, now chat gpt spits out list without hesitation
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
how do i stop cloudlfare from blocking my bot
import discord
client = discord.Client(intents=discord.Intents.all())
@client.event
async def on_message(message):
if message.content == '!test':
await message.channel.send('This is a test')
client.run(''LOLIMNOTGIVINGUMYBOTTOKENLOL')
You're spamming something or using replit
Also reset your bot token if that is what you just sent
@nimble cradle Per Rule 6, your invite link has been removed. If you believe this was a mistake, please let staff know!
Our server rules can be found here: https://pythondiscord.com/pages/rules
no i took some of the token code outand replaced it with LOLIMNOTGIVINGUMYBOTTOKENLOL so theres no way u can get into the bot and also im using a test server too so u cant nuke it or anything even if u did find the token
Fyi some of token might be reconstructable because iirc only one part of it is a security hash
hey guys, im getting this cloudflare error
things i've tried :
1.) kill 1
2.) created a new application on discord developer portal
but it didn't work.
also, im using uptimerobot to keep my bot running 24/7
Most of them don't
Whats the easiest way to check if a message contains a key from a json dict?
Maybe better to formulate it like "any of dict keys is in message"?
Code looks like the phrase in that case
any(k in message.content for k in your_dict)```
replit hacker plan 😳
Replit hacker 🥶
😭
I've been looking for hosts in Russia recently, we got no "free trial" options but hey there are pretty nice options just for 3$
github student plan? (idk if you're ineligible)
I am eligible but I doubt they would recognise hand-written text on my student ID and we don't have mails
Also hosting service will ask for card verification anyway most likely
then verify.
😳
Man I am in Russia
You can no longer use russian cards outside of Russia 😩
I have one from bank that's not under sanctions yet it doesn't work too
tf is happening in Russia 💀
no offence
at least it's not ohio
I am not into politics, economics and other unpleasant stuff (that's not the channel topic anyway) but from what I know we just got disconnected from SWIFT which does international payments and visa and mastercard stopped handling international transactions between Russia and other countries, we only got russian Mir payment systems that is accepted in some CIS countries
oh
Google/apple pay don't even work, we have MirPay and SberPay
Never even heard of those
lmao
guys i am new at making a discord bot can you give me the basic code cuz i want to learn. Thanks😀
do you have any earlier experience with python?
yea
thanks
check if you have multiple python instances running, if not that, regen your bot's token
or maybe a process_commands inside a listener
What arguements did you give
Can discord bots read a json with spaces in its keys?
Mine doesnt work if I dont use a key without spaces
hey guys! super quick question, what library should i use to create select menus? or do you not need another library and can do them in discord.py itself?
You can do them in discord.py
Here let me get the link for the example I wrote
well that should be possible, doesn't make a difference
Here you go https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py @craggy sleet
thanks
how can i take the rest of the sentence whole as an arg?? lie if i type . search this and that, it is only accepting the first word ie this as the arg how to make the arg as this and that
async def rijal(self, ctx, message):
weak = "weak"
unknown = "unknown"
if narrators[message] == weak:
await ctx.send("This hadith is **unreliable**")
elif narrators[message] == unknown:
await ctx.send("This hadith is **unknown**""E")
elif narrators[message] in unknown and narrators[message] in weak:
await ctx.send("This hadith is **unknown** and **unreliable**")```
^^^ why cant my code read a key without a space? if my key is a:1
it works fine, but if it is " a a":1, it doesnt give anything
I'm not sure what you mean by that
it's completely fine to have spaces
man pls help me how do i take the whole rest of the message as an arg
and where is it erroring, specify the line
ctx, *, message
I get no error, thats the problem
How do you know what the error is
Because when the key has no spaces, it sends the messages, but when it has spaces, it doesnt
is message the key you're searching for?
Nah, im checking if the message is a key
I mean if you run the command like !rijal a a
it will only grab the first a and leave the second one
you may want to add an asterisk before the message like here -> #discord-bots message
I dont need to put an asterik anywhere else? Only in the param?
yeah
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 108, in __getattr__
raise AttributeError(msg)
AttributeError: loop attribute cannot be accessed in non-async contexts. Consider using either an asynchronous main function and passing it to asyncio.run or using asynchronous initialisation hooks such as Client.setup_hook```
does jsk not work when creating buttons? like it just don’t create the button whatsoever?
I’m trying to jsk some code with a view which has some buttons, im passing the view when sending the message yet I’m still not getting my buttons
async def multi_word_command(ctx, *, long_sentence):
print(long_sentence)
And in discord:
!multi_word_command hello world! this sentence is composed of many different words.
Your console:
hello world! this sentence is composed of many different words.
Kind of basic here but anyone know why I get this error
nope
Well you are doing a relative import so if you don't have from then it will now look for config.py inside the executed folder.
C:.
│ config.py
│
├───bar
│ │ bot.py
│ │ cheese.py
│ │
│ └───yes
│ lol.py
│ __init__.py
│
└───foo
``` With this tree; if we launch from `bot.py` we can import `cheese.py` by doing `import cheese` or import `lol.py` using the `from` keyword. Keep in mind you need `__init__.py` for Python to see the directory. An empty one is fine.
Now we can import lol by typing `from yes import lol`. Here there also is a file called `config.py`. This package is called a top level package because it's higher than the executed file. Generally you don't want to import top level packages since it's not pretty. It's also a security risk.
I recommend to put the config lower or the bot higher. @spring flax
How would I get this to check messages even if they are in others? If I do !hadith (msg), it will run fine, but if its !hadith (msg other text) how can I get it to run? How can I get it to check if the key is in the msg?
async def hadith(self, ctx, *, message):
weak = "weak"
unknown = "unknown"
if narrators[message] in message == weak:
await ctx.send("This is **unreliable**")
elif narrators[message] == unknown:
await ctx.send("This is **unknown**")
await ctx.send(narrators.values(unknown))
elif narrators[message] in unknown and narrators[message] in weak:
await ctx.send("This is **unknown** and **unreliable**")```
Heres my json
{"Aban": "weak"}
hey I need help
do you have multiple discords installed
pycord and discord.py
run it without debug and show full traceback
Hello, can somebody help me how to make discord bot send dms from user to a selected channel?
The user would need to also assign the channel id.
and a guild ID preferably 😉
It's about a kind of ticket. To send a user's message to the bot after being sent on a private message, it was sent by the bot to the channel indicated by me
Not really.
in his case, I guess it's just a wait_for in the user's DM
Also no.
Does anyone of you using cogs does have a decent button example for me?
using discord.py
How can I check if a key from a dict is in a message string?
async def test(self,ctx, *, message):
keys = narrators.keys()
for keys in narrators:
if keys in message:
await ctx.send("e")```
However, it doesnt work
{"Aban": "weak"} heres the json dict
Attach the view to the message, has nothing to do with cogs.
Wait for is pretty heavy so using on_message is a better option.
Why not handle the chat inside his dm's then?
I'd just timeout after a while, ofc I'd set a limit
if "key" in narrators.keys():
# True if "key" in narrators keys.
Yeah, but I need the message to be checked
Depends how long the timeout is. If it's more than 15 min I'd use a on_message solution.
for sure, I was thinking like a minute
All the separate words?
I tried it this way;
@cog_ext.cog_slash(description="Kreiere einen Button!")
async def button(self, ctx: interactions.CommandContext):
button = interactions.Button(style=interactions.ButtonStyle.PRIMARY,label="Click me!",custom_id="click_me")
await ctx.send(components=button)
Yeah, just need the message to be checked if it contains any words in the dict keys
py-cord with discord components?
I need to make a kind of a tickets system
pycord with discord-py-interactions since discord components are not existing anymore
if any(word for word in message.content.split() if word in narrators.keys()):
i had it running with components.. a shame they removed it
Isn't keys() kind of redundant
Also this can be made much easier because you require them as tokens
Uh, no experience with that, sorry. Might try the py-cord official server. https://discord.gg/pycord
Thanks ill give it a go
I used this to not make it confusing.
@command(...)
async def foo(ctx: Context, *message: str) -> None:
if intersection := (set(message) & narrators.keys()):
...
*message captures each word and appends to a sequence
Rather than needing to do split
Like this?
async def test(self,ctx, *, message):
if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
await ctx.send("e")```
(added the weak, so it can scan keys with the weak value)
Give it a try. I highly recommend checking Andy's message too, more complicated but for sure more readable.
Learned that operator during advent of code & :3
set intersection for that sweet sweet O(min(len(s), len(t)))
@near wolf any comments?
reinstall dpy, remove all libraries that use discord namespace
you don't have a file named discord.py in your projects folder, do you?
that's not related, it wouldnt trigger that LOC
I have a folder called discord bot
that doesn't matter
but yeah, having third-party ~forked discord libs installed can mess things up => delete them all & reinstall dpy
Delete what discordpy?
Lol autocorrect
pip list for me
show us the output
could be, we're here to find out
hmm
nextcord is one of the issues
seems like you tried a previous shitty tutorial too 😉
Also trying it to send the key that was found in the message, but it doesn tseem to work
if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
await ctx.send("e")
elif any(unknown for unknown in ctx.message.content.split() if unknown in narrators.keys()):
unknown = "unknown"
test = unknown in ctx.message.content.split()
await ctx.send(test)```
json
```{"Aban": "weak", "test": "unknown"}```
use venvs to avoid such mess
!venv
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
I'm not sure if you've tried debugging this, I would
so what should I do?
2 options
either use venvs (you should learn them, the sooner the better)
OR
delete all python discord bot related libs and only keep the dpy one in your pip list
I opt the former
WHAT ARE LIBS?
Got no errors
Sorry for caps^^
libraries
Oh
debugging ~trying to understand what the for loop is iterating over etc, chances are, it isn't what you think it is
also, can you tell us what "message" you tried to type AND what should happen? / what the intended purpose is
How can I log the full command ran with my bot? At the moment I have py @client.event async def on_command(ctx): channel = client.get_channel(1059393082237403156) server = ctx.guild.name user = ctx.author cchannel = ctx.channel command = ctx.command await channel.send(f'`{user}` used `{command}` in `{server}` in `{cchannel}`')
But I want it to also log the peramaters (e.g *ban user1 10d)
example
!test shit should make the bot respond with "shit"
have you looked at ctx's attributes?
in the docs
no 1 sec mb
hint: something with "command"
What does venv even do
got it, message_content
The message is !test test
it should respond with the key, that was found in the dict, which is test, instead it responded with "e"
what do you think ctx.message.content.split() returns?
why aren't you using your *, message parameter?
The message sent
you should only care about the argument aka what comes AFTER the command's name
if any(key for your_dict.keys() in message.split(" "):
maybe that'll clear some things up ⏫
or even better, if you instantly want the value, related to the key
for key in your_dict.keys():
if key not in message.split(" "):
continue
await ctx.channel.send(f"The key found was {key}, the relating value is {your_dict[key]}")
return```
there's obviously more efficient ways of doing this (by for example using := and the .get() method on a dict, also splitting the message on every iteration is shit), but this is just for educational purposes
The problem with the for key in etc is that im not looking for one specific key, rather, im looking for all keys that are present in the message
in that case, you can store them in a list, and then do whatever you like with them
list_of_found_keys = []
for ... :
if key not in ...:
continue
list_of_found_keys.append(key)
# optionally, do extra stuff underneath
again, there are more efficient ways of doing this (by intersecting between 2 sets)...
How do you check for users who reacted to a message?
I tried this but it returns empty list everytime
users = await message.reactions.get(emoji).users().flatten()
- in what context are you using this ?
- what intents do you have enabled?
I'm trying to create a giveaway function for my discord bot. All intents are enabled.
also in the portal? I need to SEE it too

lastly, any error handlers by any chance?
For 14 years already 
im back how is it now
lastly, a giveaway command is VERY delicate and you have to take a lot of stuff into account:
one of them being "what if your bot restarts?"
think about that
I just want to get it working first 😄
I want to understand why it doesn't pick a winner
most likely because you need to refetch the message
Even though there are users who reacted to the message
test = await test.channel.fetch_message(test.id)
THEN get the reactions of that message
I know, shitty variable names, but you get the point
you're trying to get reactions of the message when you sent it, not after the sleep/timer hits 0
Hello, i need to create ticket system in dm with bot. Can somebody help me? (.py)
if you ctrl+f "ticket system" in this channel, you'll have loads of answers
ok, ty for helping
I'd use task and check at 12pm if there is a giveaway that needs to end then put that in a task. If the giveaway isn't today I wouldn't even bother to add it.
lastly, you should also check for giveaways which ended while the bot was offline
... that can be done by assigning a giveaway id then also saving the message id and the end time. Then get the times on startup, using a query you can get the ones that are less than a day or expired.
How can I fix this?
Defaulting to user installation because normal site-packages is not writeable
ERROR: Could not find a version that satisfies the requirement discord-components
ERROR: No matching distribution found for discord-components
81718e89734b:~$ python --version
Python 3.8.8
why are you trying this command in the first place?
To install discord-components
where did you get that from?
discord-components doesn't work with that Python version. It's also an archived package and hasn't been updated in a year or so.
oh
most likely a YT tutorial 
Discord.py has build in components.
ok
Discord.py is a very volatile library I wouldn't trust a source that's 3 months or older.
alr
thanks
Here is an example bot working with "components", we call those Views. -> https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py @frail notch
You mean like this?
message = await ctx.channel.fetch_message(message.id)
users = await message.reactions[0].users().flatten()
I still see you flatten stuff, but yeah, something like that
flatten will give error.
ok thank u
I'd also use a specific emoji to avoid strange stuff.
So what else should I use?
also, when picking a random user, I wouldn't async iterate through the whole list for that tbh
flatten was used to unnest a list, in this case your list is never nested also. So just remove it.
This URL doesn't work for me.
strange, maybe try without the highlight?
!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.11)") 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...
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 forgot ")" now it gives me a new error Code..
I'm waiting...
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
man
Capital letter
Its Not do you wanna See the code
well, I'm telling you it should be
from discord import Intents
that's the correct import
as shown above by the bot
I wrote it lowercase
every casing here is correct
Oh,thank you for helping me i try it again.
you're just blindly copy pasting whatever works for you, right?
No
I'm not
I'm watching a tutorial on how to make a ticket system
then why are you using NextCord when we told you
#discord-bots message
Because I don't know what's venvs
YT tutorials are bad for learning dpy
the bot told you
every command used in this channel which makes the bot say something is for a reason
so then where should I follow tutorials other then youtube?
official documentation mostly
dpy changes (updates / has breaking changes )too often to make YT tutorials reliable, they're outdated quickly
Oh
No wonder why every tutorial I follow I mostly get a error lol
makes sense
Just filter last 3 months should be alright.
yeah
they also use libraries etc which we don't use, so if you're asking for help, chances are way smaller of finding some, because we don't use third-party libs on top of the official dpy lib
Oh
@cedar snow Had to fix a bit of my code it works now thanks!
Too bad there isn't a tutorial that fully does it correct.
pinned msg
#discord-bots message
@cedar snow I found out why I got the error on "no imports discord.enum" its because I had another folder called discord bot
but now I have a different error
Lacks a lot of details.
you've basically copy pasted someone else's code... ofc debugging will be hard then
I think you also putted a slash command in a View class and put random variable tree there.
Remove the things you copy pasted and send the whole bot I see it's not long, let's see if that's correct first.
Let's build from there.
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.
well I fixed it but I have an bug now
there is no slash commands
@cedar snow how could I fix this?
Seperate the command and the View class.
Okay
!Intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, 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
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
@cloud dawn but wait if I separate the commands from the class "ticket_launcher" wouldn't not work?
Why not?
Error?
There is no error
The bot successfully gets on but the slash commands don't work
what should we do
???
the whole function and its decorator should be indented so it's in the class
The ticket function, I should clarify
Slash command also doesn't get synced anywhere.
Hmm he's telling me to take the slash command out of the class
it is
Also I don't mind it a lot but asking for 3th party payments is against Discord's ToS. Might be careful with that one.
That's not syncing
How can I add this?
That isn't a slash command, that's a button
@button
<t:1624385691:t>
<t:1624385691:T>
<t:1624385691:d>
<t:1624385691:D>
<t:1624385691:f>
<t:1624385691:F>
<t:1624385691:R>
<t:1624385691:t>
<t:1624385691:T>
<t:1624385691:d>
<t:1624385691:D>
<t:1624385691:f>
<t:1624385691:F>
<t:1624385691:R>
API Reference: https://discord.dev/reference#message-formatting-timestamp-styles
See discord.utils.format_dt for the discord.py implementation.
https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.format_dt
Thank R. Danny
@slate swan, I don't recommend copying the code.. like you can see there are a lot of things that needs fixing and it can take awhile.
Ok
How do I fix this???
class aclient(discord.Client):
def __init__(self):
super().__init__(intents= discord.Intents.default())
self.synced = False
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await tree.sync(guild = discord.Object(id=1059268830209257612))
self.synced = True
print("we are logged in!")
client = aclient()
tree = app_commands.CommandTree(client)
@tree.command(guild = discord.Object(id=1059268830209257612), name = 'ticket', description="you could purchase stuff!")
async def ticketing(interaction: discord.Interaction):
embed = discord.Embed(title="✘'𝘀 𝗦𝘁𝗼𝗰𝗸𝘇 - Purchase", description="""Payment Methods:
:paypal: :cashapp: :crypto:
How does it work?
- Press the purhase button below.
- Describe the amount you want to purchase.
- Describe the payment method you want to use for the deal.
- Wait until staff helps you with your deal.
- When the deal is done: you will get customer role and you can vouch.
Minimum Amount When Purchasing: 5$""", colour=discord.Color.purple())
await interaction.channel.send(embed = embed, view = ticket_launcher)
await interaction.response.send_message("Tickin", ephemeral= True)````
show what ticket_launcher is
Howd I create a list from all keys found in my message?
If my message contains a few keys, i need them added to a list
Right now, I got something like this
async def test(self,ctx, *, message):
if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
weak = "weak"
found = weak in narrators.keys()
await ctx.send(found)
await ctx.send("e")```
found = [weak for weak in ctx.message.content.split() if weak in narrators.keys()]
I should of thought of that lmao, thats elegant. Thanks alot man:
One last thing, how would I go on removing the sqr brackets and quotes?
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
!e
arr = ["a", "b", "c"]
print("---".join(arr))
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
a---b---c
@buoyant quail I have another error
it does not create the ticket channel
class ticket_launcher(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout= None)
@discord.ui.button(label = "Perchase!", style=discord.ButtonStyle.blurple, custom_id="ticket_button")
async def ticket(self, interaction: discord.Interaction, button: discord.ui.button):
ticket = utils.get(interaction.guild.text_channels, name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}")
if ticket is None: await interaction.response.send_message(f"you already have a ticket open at {ticket.mention}!!!", ephermeral = True)
else:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel=True, send_message = True, read_message_history=True)
}
channel = await interaction.guild.create_text_channel(name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}", overwrites= overwrites, reason=
f"Ticket for {interaction.user}")
await channel.send(f"{interaction.user.mention} has created an ticket!!!!")
await interaction.response.send_message(f"I've open a ticket for you at {channel.mention}!", ephemeral= True)```
if ticket is None: ticket.mention
how can it be, if it is None?
you want to change if and else i guess
where do you see that at?
Oh
so how can we change None to something else than?
depends on what you want
If there are not channels, which channel id are you going to print?
new error
@discord.ui.button(label = "Perchase!", style=discord.ButtonStyle.blurple, custom_id="ticket_button")
async def ticket(self, interaction: discord.Interaction, button: discord.ui.button):
ticket = utils.get(interaction.guild.text_channels, name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}")
if ticket is True: await interaction.response.send_message(f"you already have a ticket open at {ticket.mention}!!!", ephermeral = True)
else:
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(view_channel = False),
interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, attach_files = True, embed_links = True),
interaction.guild.me: discord.PermissionOverwrite(view_channel=True, send_message = True, read_message_history=True)
}
channel = await interaction.guild.create_text_channel(name=f"ticket-for-{interaction.user.name}-{interaction.user.discriminator}", overwrites= overwrites, reason=
f"Ticket for {interaction.user}")
await channel.send(f"{interaction.user.mention} has created an ticket!!!!")
await interaction.response.send_message(f"I've open a ticket for you at {channel.mention}!", ephemeral= True)
```
I made if ticket is true
you have send_messages in first and send_message in second
interaction user and guild.me
it works now thx
Aye, why isnt my text being read?
I did !test Abān, im using unidecode so it should remove accents
unidecode(ctx.message.content)
if any(weak for weak in unidecode(ctx.message.content.split()) if weak in narrators.keys()):
unidecode(ctx.message.content)
keys = [weak for weak in unidecode(ctx.message.content.split()) if weak in narrators.keys()]
found = ' '.join([str(elem) for elem in keys])
weak = "weak"
await ctx.send(found)
await ctx.send("e")```
^ i get no response though with accents
if i do !test Aban, it sends
json
{"Aban": "weak", "test": "unknown"}
\u0065 : LATIN SMALL LETTER E - e
!charinfo ë
\u00eb : LATIN SMALL LETTER E WITH DIAERESIS - ë
Yep
Hm, so how would I go about translating it into a normal letter?
!d unicodedata.normalize
unicodedata.normalize(form, unistr)```
Return the normal form *form* for the Unicode string *unistr*. Valid values for *form* are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.
The Unicode standard defines various normalization forms of a Unicode string, based on the definition of canonical equivalence and compatibility equivalence. In Unicode, several characters can be expressed in various way. For example, the character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).
NFC, NFKC?
That's the form you want them in.
Whats the normal form?
"The normal form KD (NFKD) will apply the compatibility decomposition, i.e. replace all compatibility characters with their equivalents. The normal form KC (NFKC) first applies the compatibility decomposition, followed by the canonical composition."
!e ```py
import unicodedata
def strip_accents(s: str) -> str:
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
print(strip_accents("Hëllo word!"))
@cloud dawn :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello word!
Cant find the unicodedata lib in my project interpreter to install?
It's a default package.
I can't get it working
Apparently you can
Footers won't render
Design flaw tbh
But description should be fine iirc
There is also a timestamp field in the actual Embed
I think that'll work too
I cannot remember if fields work too but maybe
Do you know what I'm doing wrong?
end_time = datetime.datetime.now() + datetime.timedelta(seconds=duration)
embed = discord.Embed(title=f'Giveaway: {prize}',
description=f'Ends: {end_time}',

You cannot just send a raw timestamp
Can you show me an example?
take a look
So <t:datetime.datetime.now():R>
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
My code isnt reading messages with accents even though i normalised it?
if any(weak for weak in unicodedata.normalize('NFKD', ctx.message.content.split()) if weak in narrators.keys()):
keys = [weak for weak in unicodedata.normalize('NFKD', ctx.message.content.split()) if weak in narrators.keys()]
found = ' '.join([str(elem) for elem in keys])
weak = "weak"
await ctx.send(found)
await ctx.send("e")```
json
```{"Aban": "weak", "test": "unknown"}```
The function doesn't process lists.
Damn
Just call the function when comparing.
dt = datetime.now()
end_time = datetime.timestamp(dt) + duration
embed = discord.Embed(title=f'Giveaway: {prize}',
description=f'Ends: <t:{end_time}:R>',
color=discord.Color.green())
message = await ctx.send(embed=embed)```
@pliant gulch @cloud dawn Any idea?
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.11)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
i would recommend using this instead
Scroll up 2 times
All the more reason to use format_dt
I put an asterik in the test parms before ctx, yet my code cant read a json key with spaces?
if any(weak for weak in ctx.message.content.split() if weak in narrators.keys()):
await ctx.send("e")
{"Aban b. Abi Ayyash": "weak"}
ctx.message is always <prefix>test
Unless self is ctx???
The way the command signature is written makes it very confusing
Hey
I need help
everytime I create a ticket it lets me create multiple tickets
and I am supposed to only have one
please help!
I still can't figure out how to use it 😅
discord.utils.format_dt(end_time, "R")
Im trying to make a ship command that saves the love percent
Code:
https://paste.pythondiscord.com/kiwapitohe
I keep getting this error i dont know how to fix it though im very lost
Traceback (most recent call last):
File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\app.py", line 1163, in invoke_application_command
await context.invoke()
File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\context\base.py", line 326, in invoke
await self.command.invoke(self)
File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\commands\base.py", line 690, in invoke
await self(context, **kwargs)
File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\lightbulb\commands\base.py", line 605, in __call__
return await self.callback(context, **kwargs)
File "C:\Users\Lucaq\Novemeber Project\Bologne\bologne\extensions\ship.py", line 93, in echo
insert_ship_doc()
File "C:\Users\Lucaq\Novemeber Project\Bologne\bologne\extensions\ship.py", line 73, in insert_ship_doc
collection.insert_one(ship_document)
File "C:\Users\Lucaq\AppData\Roaming\Python\Python310\site-packages\pymongo\collection.py", line 3207, in __call__
raise TypeError(
TypeError: 'Collection' object is not callable. If you meant to call the 'insert_one' method on a 'Database' object it is failing because no such method exists.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Lucaq\Novemeber Project\Bologne\bologne\__main__.py", line 43, in errorHandler
raise event.exception
lightbulb.errors.CommandInvocationError: An error occurred during command 'ship' invocation
....
I tried it out but it still doesn't work:
dt = datetime.now()
end_time = int(discord.utils.format_dt(end_time, "R"))
embed = discord.Embed(title=f'Giveaway: {prize}',
description=f'Ends: <t:{end_time}:R>',
color=discord.Color.green())
message = await ctx.send(embed=embed)
end_time = datetime.timestamp(dt) + duration
fmt_time = discord.utils.format_dt(end_time, "R")
embed = discord.Embed(..., description=f"... {fmt_time} ...")
...
#1059620769870647296 message
this answer is still relevant, dont format the username into the channel name because discord will rewrite it to something different if there are unacceptable characters in the name
Should I still keep: dt = datetime.now()
Yes
You can probably just do
from datetime import datetime, timedelta
end_time = datetime.now() + timedelta(seconds=duration)
fmt_time = discord.utils.format_dt(end_time, "R")
embed = discord.Embed(..., description=f"... {fmt_time} ...")
@young dagger 
Thank you. What if I want to use days or weeks for example?
From the docs https://docs.python.org/3/library/datetime.html#timedelta-objects
from datetime import timedelta
delta = timedelta(
days=50,
seconds=27,
microseconds=10,
milliseconds=29000,
minutes=5,
hours=8,
weeks=2
)
These are all your options
When possible can someone help me with this
hmm and how could I make a data base???
What do you think about this one?
duration_pattern = re.compile(r"(\d+)([smhd]?)")
@client.command()
async def create(ctx, duration: str, num_winners: int, *, prize: str):
# extract the duration and the unit from the duration argument
duration_match = duration_pattern.fullmatch(duration)
if duration_match is None:
return await ctx.send("Invalid duration format. Use `!create 2m`, `!create 1h`, `!create 1d`")
duration_value, duration_unit = duration_match.groups()
duration_value = int(duration_value)
# convert the duration to seconds
if duration_unit == "m":
duration_in_seconds = duration_value * 60
elif duration_unit == "h":
duration_in_seconds = duration_value * 3600
elif duration_unit == "d":
duration_in_seconds = duration_value * 86400
else:
duration_in_seconds = duration_value
# calculate the end time
end_time = datetime.now() + timedelta(seconds=duration_in_seconds)
fmt_time = discord.utils.format_dt(end_time, "R")
embed = discord.Embed(title=f'Giveaway: {prize}',
description=f'Ends: Ends: {fmt_time}',
color=discord.Color.green())
message = await ctx.send(embed=embed)```
I'm not great with Regex but if it does what I think it does it should be good
well something SQL-based is quite suitable for a discord bot, and an SQLite database is a simple place to start
learning sql: https://sqlbolt.com/
learning the built-in sqlite3 module: https://docs.python.org/3/library/sqlite3.html#tutorial
SQL seems hard
especially making the tables
Everything seems hard till you try it 😄
you can ask in #databases how to model your data, but in your case the simplest would be one table
with columns for guild_id, user_id, and channel_id
(It should also be noted that an async library such as aiosqlite is more suitable for Discord bots than sqlite3, but the syntax, etc is almost identical)
guild_id and user_id would be the unique identifier for someone's ticket channel, and if someone has a row in your table matching that then you know they created a ticket channel before, though not necessarily if that ticket channel still exists
ive done recent benchmarks and found microsecond performance with simple queries, so you dont necessarily have to jump to one - that is unless you need to make a query that can take a while, which tbf you wont know until you write one
True, it won't make much real difference in a lot of cases
speaking of async wrappers, asqlite's pretty cool for this too, especially since it was written with discord bots in mind (and by the same maintainer of dpy)
(technically i cant say discord bots with evidence, but at least it optimizes sqlite for concurrency by default)
asqlite enables wal mode by default, that's pretty nice
this is so confusing as to why its not working
but i created a few buttons and dropdowns that give roles and it works for a little bit like normal but then it randomly starts responding with 'this interaction failed'?
they work perfectly fine until a certain point where they just fail
how do you keep them persistent?
oh
super().__init__(timeout=None)
do you just put timeout=None and it should be good? in the button classes
you also need each button to have a unique custom_id, and you'll need to re-add the persistent view whenever your bot restarts
*view classes, buttons don't have timeouts views do
^
sorry thats what i meant
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
this is an example of what one of my buttons looks like
i see, i dont have view classes i just use discord.ui.View as my view
Subclass a view 
views like that can't be made persistent
by "like that" i mean one defined inside a command, not any view that was initialised directly
so should i add every view like this in my onready
not in on_ready, use setup_hook instead
on_ready can get triggered multiple times, which will make the code attempt adding the view again
!d discord.Client.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
