#discord-bots
1 messages · Page 324 of 1
ok done
output
Python 3.11.6
good
yep
now if u already have vscode opened close it
open the folder for your bot in file explorer
once u did that right click and select open in terminal option
okkk
alright
ok so changing to powershell for coding?
once u type code . it will open vscode
oohk
and the folder will become the workspace/project
it does yes
alright
@shrewd apex The thing is - rn I wam following the tutorial. I don't actually know the meaning of any of the code. In future, If I wunna do it agian, ofc i can access the tutorial. But I own't be able to do it on my own since I barely know any of these codes
you only learn with familiarity u can copy once, twice but its necessary to understand before copying third time u will be able to partially write it yourself atleast
u can go through the documentation too and read along and refer parts of the tutorial its not all code a large chunk of it is explanation as well
I understand. I really wanted to code, but am unable to find the proper tutorial, and lose interest. This has hppnd a lot of times. I don't want that to hppn agn
imho discord bots are somewhat of a more advanced endeavour without some python basics down no matter how good a tutorial is its like a building on clouds u still need a foundation
lel yeh
i just know basic python
Thnx for all the help!!! Expect more help needed coming up! JK JK
What's a virtual Environment though?
what went wrong here
u have to enable running scripts for windows its a pretty common error
Oh? How do I do that?
set-executionpolicy remotesigned
run this in power shell
think of it as an isolated space for all ur project related libraries/packages
ooohk
Ohh. ok. Then what is the actual terminal that i open
without running a code for ve
Lol getting so many errors
there 2 terminals windows cmd (command prompt) and other is powershell
feels nice
u can search it in taskbar
Ok...
powershell and run it
sure
open powershell as administrator
Oh. I did in the same one
it worked though?
it worked?
Yess
yeah then thats fine
some changes require new terminal to apply
thats why some programs after settings change also ask u to restart them
oooh ok
Ok
Now i did pip install discord.py
and it showed a rlly long output
At end and in between it shows error
show
Its rlly long
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
yeah 1 sec
oke
i think ik why u got the error just to confirm once btw run python --version in vscode terminal and tell me output
ok
new terminal?
same where ur running commands
yeah thats 1 issue
damnnnn
Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
this is second one
yh new terminal then
delete the old venv folder
so many new installations
ooohk
thats why i also asked to remove old terminal instances
done
just make sure of versions this time when following steps
oooh yh got it now sry abt tht
yup
try with 3.11 this time if u get same error install the other stuff
.
oohk
??
the visual c++ tools
So... Shoiuld i install it?
first install discord.py
oke
if it errors out then install
aight
yh
gives an error
should i install then?
yep
aight
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Lmao it's taking 17.5 gb
nvm
What all do i need to install?
1
1st one only?
yeah
yeah a few
i made pokemon bot sometime ago
WOW. Nice!!
I saw your website! It's pretty awesome! Also that pokedex site you created - AWESOME!!
ty
Lol I have been stuck on just creating and setting up discord.py for an hour.
Not even gotten to writing the actual code
ok installed @shrewd apex
all pokemons as in?
i think its likely it will just spawn another task in parallel
here is a demo altho bot is ded now
@shrewd apex Its installed, the tools
continue with the discord.py installation
yeah
nice
Ok thnx for all the help @shrewd apex
I need some help with regex
I'm using discord.py to get user messages but I want to remove the user ID before the message
I think this regex should match everything except for what's inside the <@...>
^((?!<@.*>).)*$
but it isn't working
this might be super stupid tbh
u exposed ur token
or ami doing smth wrong?
💀
reset it
and u can directly do
bot.run(os.getenv("TOKEN"))
now, is smth wrong?
well i was following the tutorial so
also make sure to replace the resetted token in .env file
yup
yeah u dont need to add the TOKEN in the code
ooooh ok makes sense!!
yuppp thats why i get it!
Okk
and the next code is in python
the main code. Do i put token in there too?
so i can let "TOKEN" be?
Yeah thats what. In python I shpuld let that be right?
yep
oke
thnx!!
@shrewd apex Do you know any other places to code like python (it's killing my eyes)
what?
What I meant was, I have seen other places where I can code in python. Where do you code? Like the proper IDLE? Ik my question is very vague but still?
idle aint proper at best its classic for like very small programes
if u dont like the theme u can change it
ooh yh thats waht i was askingg
i can? how?
the light color although my pc is at dark mode
or for inbuilt ones press cntrl+shift+p to open command pallete then type theme
So for coding in vscode do i need to open a new file in the same folder?
ooh ok
?
does anybody know how to fix this [{
"resource": "/home/abal10001/discord bot/main.py",
"owner": "generated_diagnostic_collection_name#0",
"code": {
"value": "reportMissingImports",
"target": {
"$mid": 1,
"path": "/microsoft/pyright/blob/main/docs/configuration.md",
"scheme": "https",
"authority": "github.com",
"fragment": "reportMissingImports"
}
},
"severity": 4,
"message": "Import "discord_slash" could not be resolved",
"source": "Pylance",
"startLineNumber": 10,
"startColumn": 6,
"endLineNumber": 10,
"endColumn": 19
}]
i was trying to install discord slash commands
yeah
use discord.py no?
it supports slash commands
I use discord py
Uhm, anyone have a clue please?
I'm trying to make a discord bot and trying some shit out
I'm a beginner
discord_slash
u need intents
!intents
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.
ty
so if i want to have a command give the result in an embed, what do i do?
check the embeds page in the guide
I did, it doesn't include that
huh?
Help please [{
"resource": "/home/abal10001/discord bot/main.py",
"owner": "generated_diagnostic_collection_name#0",
"code": {
"value": "reportMissingImports",
"target": {
"$mid": 1,
"path": "/microsoft/pyright/blob/main/docs/configuration.md",
"scheme": "https",
"authority": "github.com",
"fragment": "reportMissingImports"
}
},
"severity": 4,
"message": "Import "discord_slash" could not be resolved",
"source": "Pylance",
"startLineNumber": 10,
"startColumn": 6,
"endLineNumber": 10,
"endColumn": 19
}]
What is this
Im trying to install slash commands
look at overview
how
Is this an error thrown in the console?
no in the terminal
Ok 👍
Could you take a screenshot?
You’re throwing us a random array with 0 context
What should i take screenshot of
how are u installing?
It didnt send anything
what
Yh
take a screenshot of the error
I said wrong
You’re being incredibly confusing right now
oh lmao
Those are warnings from your IDE, not exceptions
What does that mean?
Discord.py have natively supported slash commands, so there’s 0 reason to be using discord_slash
no idea what is even the package
So I should just add the slash.slash command
No. discord.py natively supports slash commands, there’s no reason to use any extensions.
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This is a guide on how to create them
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
!pypi discord-py-slash-command
just found it
they renamed themselves to discord-interactions
btw guys anyone free to review https://fallendeity.github.io/discord.py-masterclass/slash-commands/ ty 🙏
A hands-on guide to Discord.py
this and hybrid commands pages
oh for a second i thought they had three different packages hosting the same code, but discord-interactions looks like a different project
https://stackoverflow.com/questions/67502375/how-can-i-get-easily-started-with-discord-slash-python-module not sure my source is this stackoverflow answer
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
So guys how do i fix this problem?
pip install discord-py-slash-command run this in ur terminal
ah, discord-interactions is the subdomain for their old docs site... so we have discord_slash, discord-interactions, discord-py-slash-command, interactions.py, and discord-py-interactions which have all been used by the same library, albeit for different versions
https://paste.pythondiscord.com/GZWA - This is given on the tutorial site. It is for using slash and prefix commands at once. I am very confused as to how this works. If someone would be kind enough to tell me I would be very grateful!!

just send this Requirement already satisfied: discord-py-slash-command in /home/abal10001/.local/lib/python3.9/site-packages (4.2.1)
Requirement already satisfied: aiohttp>=3.8.1 in /home/abal10001/.local/lib/python3.9/site-packages (from discord-py-slash-command) (3.8.6)
Requirement already satisfied: frozenlist>=1.1.1 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (1.4.0)
Requirement already satisfied: attrs>=17.3.0 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (22.2.0)
Requirement already satisfied: multidict<7.0,>=4.5 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (6.0.4)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (4.0.3)
Requirement already satisfied: yarl<2.0,>=1.0 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (1.8.2)
Requirement already satisfied: aiosignal>=1.1.2 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (1.3.1)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (3.0.1)
Requirement already satisfied: idna>=2.0 in /home/abal10001/.local/lib/python3.9/site-packages (from yarl<2.0,>=1.0->aiohttp>=3.8.1->discord-py-slash-command) (3.4)
thats hybrid commands
what u sent is only the bot class so far
?
discord-py-slash-command==3.0.3 is the latest version of discord_slash, but they've since moved on to interactions.py which no longer monkeypatches discord.py
Thanks for your help, I've now got it working. Hoorah!
cool
'
aight
Asher it sent this when i runned the pip Requirement already satisfied: discord-py-slash-command in /home/abal10001/.local/lib/python3.9/site-packages (4.2.1)
Requirement already satisfied: aiohttp>=3.8.1 in /home/abal10001/.local/lib/python3.9/site-packages (from discord-py-slash-command) (3.8.6)
Requirement already satisfied: frozenlist>=1.1.1 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (1.4.0)
Requirement already satisfied: attrs>=17.3.0 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (22.2.0)
Requirement already satisfied: multidict<7.0,>=4.5 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (6.0.4)
Requirement already satisfied: async-timeout<5.0,>=4.0.0a3 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (4.0.3)
Requirement already satisfied: yarl<2.0,>=1.0 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (1.8.2)
Requirement already satisfied: aiosignal>=1.1.2 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (1.3.1)
Requirement already satisfied: charset-normalizer<4.0,>=2.0 in /home/abal10001/.local/lib/python3.9/site-packages (from aiohttp>=3.8.1->discord-py-slash-command) (3.0.1)
Requirement already satisfied: idna>=2.0 in /home/abal10001/.local/lib/python3.9/site-packages (from yarl<2.0,>=1.0->aiohttp>=3.8.1->discord-py-slash-command) (3.4)
pip install discord-py-slash-command==3.0.3 as gamecracks sent
It still says i have problems
This bot template can be used for both slash commands and regular commands or hybrid commands.
can be used for .
Yh. So I don't need to know it completely?
no it went away
nvm i'll see that
to add a simple ping command u can add as the following
@bot.tree.command()
async def ping(inter: discord.Interaction) -> None:
"""Gets bot latency!"""
await inter.response.send_message(f"> Pong! {round(bot.latency * 1000)}ms")
u can take a look at hybrid commands and slash commands page
Ok!
When i runned the bot it sent this cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
File "/home/abal10001/discord bot/main.py", line 10, in <module>
from discord_slash import SlashCommand, ButtonStyle
ImportError: cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
My Error:
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\modal.py", line 268, in _scheduled_task
await self.callback(interaction)
File "c:\Discord\Maja Projekt\Maja-Beta\modules\ticket_system\view.py", line 529, in callback
await message.edit(view=self)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\message.py", line 1533, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 399, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
*I want to edit the buttons after the modal
Can anyone tell me what all i have to replace her? I'm a little confused
Hello, I'm working on a bot called vision and our aim is to make a simple non-dashboard easy to setup and use bot for medium sized servers of the range 200-5000 members and I'm kind of looking for some people to help me develop it and advise with the embeds etc, if you're looking to join please hit me up!
Anyone?
somewhere in your code you are trying to add a component that is not available in this context
available ones are (2, 3, 5, 6, 7, 8) meaning button, select
So how can i edit them in after the modal
the chapter looks neat, pretty comprehensive, and well organized
some suggestions:
- at the start, "client-integrated interactions" could be written as application commands for consistency
- the starting note about global/guild-specific commands becomes redundant in the following sections
- in "Creating a Slash Command" i would clarify between locally defining a slash command and creating the command on discord, and then also move the bits about syncing from the last section so the explanation is more cohesive
- a sentence about using docstrings for describing parameters would be helpful, otherwise readers would only be aware of it if they clicked the tab to reveal the docstring example
- doc links for each d.py function/class introduced like
app_commands.describe()would be nice - in "Sending Responses" the warning style seems a bit superfluous and could be omitted for readability
- in "Sending Followups" the warning block could be merged into the above paragraph, something like "Once an interaction has been responded to, you can only send followup messages by ..."
- in "Slash Command Parameters" the annotations like "A string parameter" are redundant and can be omitted
- as per the discord API docs, i would rename the "User Menus" and "Message Menu" sections to "User Commands" and "Message Commands" respectively
- in the "Localization" section, i suggest mentioning that programs are usually translated by hand with stuff like project fluent or gettext (of which i have a repository to teach its usage in dpy)
as for hybrid commands, i would talk about it after slash commands so you can cross-reference that chapter and avoid repetitive information
ty time to read thru 🙏
I want to replace the hello with a command. Should i put the prefix before it or no? Should i send the code?
@shrewd apex ?
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
ah fair for localization i was looking more towards like one time translation and dumping
?
I need help when i runned the bot it sent this cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
File "/home/abal10001/discord bot/main.py", line 10, in <module>
from discord_slash import SlashCommand, ButtonStyle
ImportError: cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
@lethal hemlock
Yh
i downloaded smth else but how do i fix this problem
cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
File "/home/abal10001/discord bot/main.py", line 10, in <module>
from discord_slash import SlashCommand, ButtonStyle
ImportError: cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
@hushed galleon Could you pls tell me this? I desperately need to move from here
Send it in not a screenshot also no u would define the prefix seperately
Ohh ok thnx!!
also how do i start my bot?
I want to see of it atleast replies to 1 command
In my private server
?
Alright well you’d run the bots code no?
In your private server
uhmm how? Like i just click run in VS?
You’d create a file named something like ‘Discord bot’ inside will be your discord code and in the language like python for example run the main.py which will run the bot
Ok
If you want 24/7 hosting you need to use webhosting or vps server. If you are just testing its fine to just run in and temporarily have the bot online running in locally
the code? sure
The error
thats all it shows when i run it
I meant copy and paste it here
Import os
#like this
load_dotnev()
ooh ok
`import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("TOKEN")
bot = commands.Bot(command_prefix="s!", intents=discord.Intents.all())
@bot.event
async def on_ready() -> None:
print(f"Logged in as {bot.user}")
bot.run(TOKEN)`
@slate swan
Oh thanks can you do the same with the error maybe
sure
“(venv) PS C:\Users\udayg\Documents\Stardew bot> & "c:/Users/udayg/Documents/Stardew bot/venv/Scripts/python.exe" "c:/Users/udayg/Documents/Stardew bot/bot.py" 2023-11-25 01:42:08 INFO discord.client logging in using static token Traceback (most recent call last): File "c:\Users\udayg\Documents\Stardew bot\bot.py", line 31, in <module> bot.run(TOKEN) File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 860, in run asyncio.run(runner()) File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 664, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 849, in runner await self.start(token, reconnect=reconnect) File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 777, in start await self.login(token) File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 609, in login raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead') TypeError: expected token to be a str, received NoneType instead (venv) PS C:\Users\udayg\Documents\Stardew bot> “
Okay so u have a .env ?
Yup
It could be 1 of 3 things ill start with the first thing
The .env isnt in the correct location
The .env should be in same directory as ur script right?
It's in the folder
yup, same folder
Do u have a line similar to this in there?
TOKEN=. The os.getenv("TOKEN")
I have this:
TOKEN=<the actual token>
like that
?
See if load_dotenv() function is being called before os.getenv("TOKEN").
How do I get a username from a users ID?
Put this below the load_dotenv line
print(os.environ)
You need to get the user object with the user ID then get the username from the object.
now should i run it?
fetch_user method maybe?
yeah try it should check if the environment variable is being set correctly by printing out the value of os.environ after calling load_dotenv().
ok
How does one do that?
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
!d discord.Client.fetch_user
await fetch_user(user_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User) based on their ID. You do not have to share any guilds with the user to get this information, however many operations do require that you do.
Note
This method is an API call. If you have [`discord.Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members) and member cache enabled, consider [`get_user()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_user) instead.
Changed in version 2.0: `user_id` parameter is now positional-only.
Something like this
@bot.event
async def on_ready():
user_id = 1234567890 # Replace this with the user's ID
user = await bot.fetch_user(user_id)
username = user.name
print(username)
@slate swan https://paste.pythondiscord.com/7LXQ
Oh awesome thank you!
Check its formatted like this ur env
TOKEN=your-bot-token-here
And it should be setup correctly really? You could tru doing both of these
pip uninstall python-dotenv
pip install python-dotenv
Can you share your entire code?
Show me the code you have then i'll guide you.
I figured it out thank you though
why does nothing work after this line, i am trying to add something to an empty file but nothing wroks after this
alldata2 = ast.literal_eval(cont.decode('utf-8'))
!d ast.literal_eval
ast.literal_eval(node_or_string)```
Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, `None` and `Ellipsis`.
This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
yea?
What is cont
cont = await file.read()
Is there an error?
nopejust nothing happens
i tried doing an exception and got this
An error occurred: invalid syntax (<unknown>, line 0)
What are the contents of the file
nothing
what
Do you what ast.literal_eval() does
I have a suspicion you think it does something it doesn't

ive just sent an empty file to a channel and i want to insert smthn into it
.
so where did literal_eval come from?
uhh i cant remmeber ive just come back to some code from a while ago
but i have the exact same code and it works
but this version doesnt
i think the file shouldnt be empty
so you are saying you use literal_eval to insert text into a file?
So if you don't know what it does, why is it there
ive used it before and it works
But you don't know what it does
if you know it works why you ask us
i want to know why this version of the same code doesnt work
..
Read this
!d ast.literal_eval
ast.literal_eval(node_or_string)```
Evaluate an expression node or a string containing only a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, `None` and `Ellipsis`.
This can be used for evaluating strings containing Python values without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.
Evaluate an expression node or a string containing only a Python literal or container display.
First, learn what it actually does
what makes you think its for inserting text into file
i domt know
nor do i
So why do you think it does that?
cuz its worked in the same copy of my other code
It obviously doesn't write to files
thats not even related to discord bots
Share the full code
@bot.command()
@commands.cooldown(1, 2, commands.BucketType.guild)
async def loa(ctx, userID=None, amt_time=None):
support = ctx.guild.get_role(SUPPORT_ID)
if support in ctx.author.roles:
if userID is None or amt_time is None:
await ctx.reply(f"Invalid usage.\n*`usage: {PREFIX} userID time in days`*")
return
else:
try:
print(1)
dbchannel = bot.get_channel(1155888521840693359)
messages = [message async for message in dbchannel.history(limit=1)]
print(2)
while len(messages) == 0:
print(3)
messages = [message async for message in dbchannel.history(limit=1)]
messages = messages[0]
print(4)
file = messages.attachments[0]
print(5)
cont = await file.read()
print(6)
alldata2 = ast.literal_eval(cont.decode('utf-8'))
print(7)
alldata2.append({"userID": userID, "time": amt_time})
print(8)
await loa_logs(alldata2, messages, dbchannel)
await ctx.reply(f"Successfully added <@{str(userID)}> to the database.")
except Exception as e:
print(f"An error occurred: {e}")```
Is this your code?
yes it is my code
I'd assume loa_logs is writing the file
Though it's your code, so I'm a bit confused how you don't know where it's occuring
i know
async def loa_logs(data, messages, dbchannel):
buffer = io.StringIO()
buffer.name = "loa.py"
buffer.write(str(data))
buffer.seek(0)
await messages.delete()
await dbchannel.send(file=discord.File(buffer, 'loa.py'))```
this is loa logs
i know ur gonna comment on stringio
how do i send a file with something in?
You're already doing it
The issue isn't with sending the file though
The file you're getting from the message is empty
So when you try to evaluate the content it throws an error
oh i see
dbchannel = bot.get_channel(1155888521840693359)
messages = [message async for message in dbchannel.history(limit=1)]
print(2)
while len(messages) == 0:
print(3)
messages = [message async for message in dbchannel.history(limit=1)]
messages = messages[0]
print(4)
file = messages.attachments[0]
print(5)
cont = await file.read()
print(6)
alldata2 = ast.literal_eval(cont.decode('utf-8'))
print(7)
alldata2.append({"userID": userID, "time": amt_time})
This whole block is also incredibly hard to read
Lots of spaghetti code
huh?
The while statement is redundant
oh
Why are you using literal_eval in the first place
A dropdown would be a way better representation for all the messages
i just want to know how i can fix nothing appending
Let's start from the beginning. What is the purpose of literal_eval
to evaluate the content
Okay, can you show an example content from the file
the file is empty
It shouldn't be empty though, correct?
yes
Could you show an example of what should be in the file?
[{"userID": 1037772222145765406, "time": 3}]
Okay, and what effect does literal_eval have on the content? Why are you using it?
tbh im not really sure
So if you don't know what it does, and why you're using it, you should remove it
but i know it works
It obviously doesn't work if it's giving an error
it works fine in my other copy
Okay, but it's not working now
You literally do not know what it's doing
It shouldn't be there
what do i replace it with
Nothing
append wont work on a str
What even is this setup
Are you saving database files in a channel and then accessing them?
wdym
Like an actual .db file
Why do it through a channel
It just makes everything more difficult
It's definitely not
it is
It's the whole reason we're here, and you've asked many previous questions on fixing issues regarding it
It's caused a ton of issues and restrictions
it hasnt its been fine throught my whole 4k lines of code, its just now when ive decided to make the same replica of another part of my code that it doesnt work
and i think its because the file shouldnt be empty
I'm not going to help with this further. Storing database files in a channel, especially as a txt or json comes with major disadvantages, drawbacks and complications
okay fine, its not like we were getting anywhere anyway
Not braining moment: a bool is false or true right?
yea
The main.py?
Yes
Ok, I'll send
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
print(os.environ)
TOKEN = os.getenv("TOKEN")
bot = commands.Bot(command_prefix="s!", intents=discord.Intents.all())
@bot.event
async def on_ready() -> None:
print(f"Logged in as {bot.user}")
bot.run(TOKEN)```
For sure? But I followed this tutorial - https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/#prerequisites
A hands-on guide to Discord.py
what's your issue
The bot isn't starting when I run the code
where's your .env file
In the folder itself
Yup
can you screenshot your current directory
Do the folder right?
TOKEN = <MY TOKEN NAME>
yes
TOKEN=bot_token_here
yes
And you've ran
pip install discord.py python-dotenv
As I said, I just followed this guide here. and it just did pip instal discord.py
Can you pip install python-dotenv
and then add a print(TOKEN) under the variable TOKEN
Yes. The bot isn't starting up
Yup
Are you sure you've enabled the intents at the discord developer portal?
Yes I have
What's the error you are actually getting?
Yes, but it's still the received None type instead of str stuff, correct?
Yes!
The same error
According to 6 hours ago
(venv) PS C:\Users\udayg\Documents\Stardew bot> & "c:/Users/udayg/Documents/Stardew bot/venv/Scripts/python.exe" "c:/Users/udayg/Documents/Stardew bot/bot.py"
2023-11-25 01:42:08 INFO discord.client logging in using static token
Traceback (most recent call last):
File "c:\Users\udayg\Documents\Stardew bot\bot.py", line 31, in <module>
bot.run(TOKEN)
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 664, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 609, in login
raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
TypeError: expected token to be a str, received NoneType instead
(venv) PS C:\Users\udayg\Documents\Stardew bot>
Yes this
can you print token
Where?
just print(TOKEN) under the line where you do TOKEN= in the main.py
oh ok
it should print the token you put in the .env file
And you're using discord.py, right
Yes
I'm pretty sure I am
Ok so now I run it?
Yes
Ok
The issue is, the token being passed is None
It has nothing to do with the bot at the moment
Shows the same error
That's not the goal
Should I reset it?
It has nothing to do with the bot at the moment
When the token was printed, was your actual token printed or None?
Oh ok
the code looks right, I think your .env file is incorrect
I wasn't printed
Nothing was printed at all?
Comment out the bot.run(TOKEN) line by putting a # in front of it
The token wsn't printed and it game the same nonetype error
Ok sure
We want to see if it's getting the token correctly
Was None printed to console?
As said earlier
We're trying to figure out why it's not being properly passed
It does give bot.run (TOKEN) in the 3rd line of output
Traceback (most recent call last):
File "c:\Users\udayg\Documents\Stardew bot\main.py", line 20, in <module>
bot.run(TOKEN)
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\udayg\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 664, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\udayg\Documents\Stardew bot\venv\Lib\site-packages\discord\client.py", line 609, in login
raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
TypeError: expected token to be a str, received NoneType instead```
I don't think you quite understand what we're trying to do
Could you share the current code?
I don't. Actually i'm just beginning to code like this (I just know basic python)
ok
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("TOKEN")
print(f"Token: {TOKEN}\nType: {type(TOKEN)}")
Could you create a new Python file in the same directory and run this.
ok
Just name it test.py or something, it's just a test.
CURRENT CODE:
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
print(os.environ)
TOKEN = os.getenv("TOKEN")
print(TOKEN) #bot.run(TOKEN)
bot = commands.Bot(command_prefix="s!", intents=discord.Intents.all())
@bot.event
async def on_ready() -> None:
print(f"Logged in as {bot.user}")
bot.run(TOKEN)```
Yes, I'm gunna do that
@latent jay
Just copy and paste this code into the test.py
and when you run it?
Gives this
that doesn't even make sense? @final iron
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
print(os.environ)
TOKEN = os.getenv("TOKEN")
print(TOKEN)
bot = commands.Bot(command_prefix="s!", intents=discord.Intents.all())
@bot.event
async def on_ready() -> None:
print(f"Logged in as {bot.user}")
#bot.run(TOKEN)
do this
My guess is your .env file is not being saved and/or accessed
which is why it's showing as NoneType
So i'd double check that.
@latent harness
Ok and how do i do that? Save it properly or smth?
Press the .env file from the left tab in Visual Studio Code and press CTRL S
Ok i did that
then run this
Could you show the entire console?
I think it worked
Did it print your token at the bottom?
It did!
yes and the bot is online
Thanks!
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("TOKEN")
bot = commands.Bot(command_prefix="s!", intents=discord.Intents.all())
@bot.event
async def on_ready() -> None:
print(f"Logged in as {bot.user}")
bot.run(TOKEN)
Just change your code to this then.
Yes, you weren't saving it after typing into it
if you see this, it means 1 file is not saved in your directory
ooooh ok
If you ever edit your env file again, make sure to save it.
Yup
And also, Do i run the main code too?
Ok so no need?
no need for what?
you should have only .env and main.py in your directory
You only run main.py
you should run whatever your main file is
Ok!
I don't know what's in your bot.py
ohk
I am really new to this (trying to make my first bot)
So I'm rlly sorry if I disturbed you in anyway
You should learn some more Python before continuing creating your Bot though. Most of the stuff we were asking you to do for testing was pretty low leveled.
THNX! @latent harness
Ooh ok, I'll look into it
without some more basic python knowledge you're going to be running into errors very frequently
hmm
But good luck
I am doing @bot then ping. Why doesn't it work?
It doesn't give me anything back
Did you save and rerun your code?
yes
Yes I'm pretty sure. I did CTRL + S then I ran it
?
It works when I do just Hello
as it's and event
but commands won't work
ok it works nvm
I have seen thatCommands are case sensitive
How do i make to non sensitive to case?
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group).
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str) using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
@bot.command(case_insensitive=True)
If you want all your commands to be case insensitive you can use the same argument in commands.Bot
Ooh ok
ok thanks!!
so here?
Yessir
oke!!
thnx!
Also. I am amaking a bot that will include lots of sprites (like armour weapons crops adn other stuff) So should I make them first and the continue to put commands?
if you have a basic idea about how and where you're gonna use the sprites, and the path to their files you can just use a placeholder for them and continue your code
Actually, I don't have any idea XD. I don't know how i can register them in
You can use a database.
What's a database?
A database is an organized collection of structured information, or data, typically stored electronically in a computer system.
So to say it easily,
It can help you organize the amounts of sprites (armors and stuff) each user has.
Using databases can also save progresses.
Ohh ok makes sense
hmmm nice!!
So is taht how bots like tatsu, OwO work?
Yes.
Oh ok. How do I make a database then?
Do you want to go to DM's or should I explain here?
Any would work, but i would prefer DMs since its a bit convenient
i personally would make my own CDN to store the sprites
What's a CDN?
Yes. naming them, introducing in code etc.
CDN is like a image hosting service that stores images on a web endpoint instead of a file on your computer
How many sprites do you have
I've worked on a project with over 1000 sprites stored in my computer
the storage it used was insane
I haven't started making them although I will have around 200 atleast (my estimate)
you can save them locally then
Assuming they're not too large in size
as for how to start, just use a placeholder file instead of the actual sprite
they might be in mbs sometimes. Wait they need to be .jpeg or .jpg right?
.png works too
yh tht asw
Ok, now I am creating a database for sprites in sqllite3. Any easy way to do it would be appreciated!! Although I am following a guide!
Keep in mind you should be using an asynchronous driver like asqlite
Tutorials are also flawed for these purposes so it's generally discouraged to use them
Whats a driver?
sqlbolt is an excellent learning resource
sqlbot?
Library that allows you to interface with the database
website
im using sqllite3
asqlite is an asynchronous wrapper of sqlite3 as it's blocking
Lol I won't be able to understand that
nvm
Not using an asynchronous driver is not an option
It's a requirement
Sooner or later you'll start receiving errors and the bot will start breaking
Better to do it properly now then have to find, and migrate your entire code later on
Ok so what exactly do i have to do?
I did this much(I just knew lil bit of actual sql)
View the example on the asqlite github
@glacial sail Look I really hope I'm on topic here but WoC's hogging all the Singapore E-Girls and you're just letting them and if you could tell them to unban me that would be great 'cause I rep EECS 'cause they can actually code
And I wasn't quite done yappin' don't put discord bots on your apps BTW I'll reject you myself if I see it
As an intern I'll reject you
!ban 1052944961722654851 Seems like you're just here to rant incoherently
:incoming_envelope: :ok_hand: applied ban to @faint charm permanently.
hi, is there someone who is developing a Bot that uses oauth2 functionalities? i need some feedbacks for my extension design (tho everything is still not documented)
does anybody know the issue with this cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
File "/home/abal10001/discord bot/main.py", line 10, in <module>
from discord_slash import SlashCommand, ButtonStyle
ImportError: cannot import name 'InvalidArgument' from 'discord' (/home/abal10001/.local/lib/python3.9/site-packages/discord/init.py)
discord_slash is a third party library and even the version you are using is very outdated as such it's hard for anyone to help you
its recommended to use the latest discord.py
!pypi discord.py use this to rewrite your code
Does anybody know how to make a ticket code? so you click a button and then it opens for you?
So how can i edit them in after the modal
Are you using discord.py?
My Error:
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\modal.py", line 268, in _scheduled_task
await self.callback(interaction)
File "c:\Discord\Maja Projekt\Maja-Beta\modules\ticket_system\view.py", line 529, in callback
await message.edit(view=self)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\message.py", line 1533, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 399, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
*I want to edit the buttons after the modal
How to properly get value out of modal to select component creating it and then out of the dropdown to the view
problem:
i have a config represented in a dataclass for example:
@dataclass
class GuildConfig:
prefix: str
something: int
now i want to create a dropdown with all available things to change and then when selcted modal pops up where you enter new value for setting
im kind of stuck how to retrieve this new value to the original GuildConfig class and then save changes to database when button clicked
maybe im overcomplicating it but thanks for any help
Yh
me when delete and send again
My bot is not showing or allowing me to make slash commands to it. Asked GPT to check my script to see if there were any errors, it said not. Wondering what nexts steps in troubleshooting would be.
reading acutal documentation and tutorial on how to do so
did u sync ur commands
Yes.
https://fallendeity.github.io/discord.py-masterclass/slash-commands/ these two https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f are good sources to get started the discord.py repo has examples as well
A hands-on guide to Discord.py
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
import discord
from discord import app_commands
from discord.ext import commands
class General(commands.Cog):
group = app_commands.Group(name="utility", description="Utility commands")
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@group.command(name="ping", description="Get the bot's latency")
async def ping(self, inter: discord.Interaction) -> None:
await inter.response.send_message(f"Pong! {round(self.bot.latency * 1000)}ms")
@app_commands.command(name="echo", description="Echo a message")
async def echo(self, inter: discord.Interaction, message: str) -> None:
await inter.response.send_message(message)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(General(bot))
With the commands.Cog class above, how would this look when I run the index.py
Still trying to work on my logic behind building my scripts so need a hand every now and then lol
u would loads the cogs from setup_hook in ur bot class
How'd that look? Is there an example?
A hands-on guide to Discord.py
cogs/
- general.py (ur cog code)
main.py (ur bot code)
.env (file for storing token)
python main.py to run
Hey @shrewd apex can you mayby help on my problem to edit buttons after a modal?
lemme take a look
My first attemp
My Error:
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\modal.py", line 268, in _scheduled_task
await self.callback(interaction)
File "c:\Discord\Maja Projekt\Maja-Beta\modules\ticket_system\view.py", line 529, in callback
await message.edit(view=self)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\message.py", line 1533, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\http.py", line 399, in request
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).```
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
u mean the .disabled right?
Yeah
await message.edit(view=self)
self is a modal here no?
Ig yes
But i want to edit the 3 buttons from the other class
After the modal
I tried it but the buttons are not peristent anymore
1 is wait for modal to complete in the view and then edit
2 is pass the view to the modal or make it an attribute
How can i do it?
!d discord.ui.Modal.wait
await wait()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the view has finished interacting.
A view is considered finished when [`stop()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.Modal.stop) is called or it times out.
I thought it was only there for views
@nc.ui.button(label="Close Ticket", style=nc.ButtonStyle.red, row=1, emoji=config.a_lock)
async def close_ticket(self, button: nc.ui.Button, inter: Interaction):
if await self.check_staff_permissions(inter):
modal = TicketCloseReason()
await inter.response.send_modal(modal=modal)
await modal.wait()```
So right?
yeah
if await self.check_staff_permissions(inter):
modal = TicketCloseReason()
await inter.response.send_modal(modal=modal)
await modal.wait()
if modal.value is None:
return
elif modal.value:
button.disabled = True
self.delete_ticket.disabled = False
self.open_ticket.disabled = False
await inter.response.edit_message(view=self)```
So should it work
yeah
But it dont edit it
print(modal.value)
also i am not sure how nextcord editing works
in dpy its await inter.edit_original_response()
Nothing happens
i meant whats modal.value?
nothing was printed
@nc.ui.button(label="Close Ticket", style=nc.ButtonStyle.red, row=1, emoji=config.a_lock)
async def close_ticket(self, button: nc.ui.Button, inter: Interaction):
if await self.check_staff_permissions(inter):
modal = TicketCloseReason()
await inter.response.send_modal(modal=modal)
print(f" Test 1 {modal.value}")
print(f" Test 2 {modal.values}")
await modal.wait()
if modal.value is None:
return
elif modal.value:
button.disabled = True
self.delete_ticket.disabled = False
self.open_ticket.disabled = False
await inter.response.edit_message(view=self)```
After wait() it prints nothing
class TicketCloseReason(nc.ui.Modal):
def __init__(self):
super().__init__(f"Closing Ticket")
self.reason = nc.ui.TextInput(label="Reason", placeholder="Enter the reason for closing the ticket here")
self.add_item(self.reason)
async def callback(self, inter: Interaction):
info = Embed(title=f"{config.a_lock} Ticket closed!", description=f"{inter.user.mention} has closed this Ticket. The ticket can now be deleted or reopened.\n\n __Reason__\n{self.reason.value}", colour=config.red)
await inter.response.send_message(embed=info)```
u need to set attribute value / values in the modal
if not u will get attribute error
Where do i have to put the value attribute
class TicketCloseReason(nc.ui.Modal):
def __init__(self):
super().__init__(f"Closing Ticket")
self.submitted = False
self.reason = nc.ui.TextInput(label="Reason", placeholder="Enter the reason for closing the ticket here")
self.add_item(self.reason)
async def callback(self, inter: Interaction):
info = Embed(title=f"{config.a_lock} Ticket closed!", description=f"{inter.user.mention} has closed this Ticket. The ticket can now be deleted or reopened.\n\n __Reason__\n{self.reason.value}", colour=config.red)
await inter.response.send_message(embed=info)
self.submitted = True
@nc.ui.button(label="Close Ticket", style=nc.ButtonStyle.red, row=1, emoji=config.a_lock)
async def close_ticket(self, button: nc.ui.Button, inter: Interaction):
if await self.check_staff_permissions(inter):
modal = TicketCloseReason()
await inter.response.send_modal(modal=modal)
await modal.wait()
if modal.submitted:
button.disabled = True
self.delete_ticket.disabled = False
self.open_ticket.disabled = False
await inter.response.edit_message(view=self)
else:
return
I try it
Still no edit

add print statements to debug where its going wrong
Okay
await modal.wait()
will not be performed
oh yeah i forgot to tell u need to include self.stop() in last line of the modal callback
C:\Users\admin\Desktop\The-MP>python client.py
Traceback (most recent call last):
File "client.py", line 79, in <module>
main()
File "client.py", line 74, in main
bot.run(config["botkey"])
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 848, in runner
async with self:
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 298, in __aenter__
await self._async_setup_hook()
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 204, in _async_setup_hook
await super()._async_setup_hook() # type: ignore
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 551, in _async_setup_hook
self.http.loop = loop
AttributeError: 'Client' object has no attribute 'http'
Keep getting this error when attempting to run 'python client.py'.
I've added self.client = aiohttp.ClientSession() to the setup_hook function.
Also imported aiohttp.
whats ur discord.py version?
wait try renaming the file to main.py and run
Traceback (most recent call last):
File "main.py", line 79, in <module>
main()
File "main.py", line 74, in main
bot.run(config["botkey"])
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 616, in run_until_complete
return future.result()
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 848, in runner
async with self:
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 298, in aenter
await self._async_setup_hook()
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 204, in _async_setup_hook
await super()._async_setup_hook() # type: ignore
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 551, in _async_setup_hook
self.http.loop = loop
AttributeError: 'Client' object has no attribute 'http'
Done that.
!paste ur bot code here
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
I'm a beginner so please be patient if I'm being stupid but what does this mean?
class Client(commands.Bot):
client: aiohttp.ClientSession
def __init__(self, prefix: str, ext_dir: str, *args: typing.Any, **kwargs: typing.Any) -> None:
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
self.logger = logging.getLogger(self.__class__.__name__)
self.ext_dir = ext_dir
self.synced = False
super().__init__(*args, **kwargs, command_prefix=commands.when_mentioned_or(prefix), intents=intents)
u forgot this line
response.text is not a valid json format
Ah, thank you I'm following a YouTube tutorial and it worked so I'm guessing it's outdated or something?
Done, bot starts but commands haven't registered.
assuming commands are in a cog u havent loaded the cogs either
I thought:
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Whitelist(bot))
would load the cogs?
where does response come from here?
async def _load_extensions(self) -> None:
if not os.path.isdir(self.ext_dir):
self.logger.error(f"Extension directory {self.ext_dir} does not exist.")
return
for filename in os.listdir(self.ext_dir):
if filename.endswith(".py") and not filename.startswith("_"):
try:
await self.load_extension(f"{self.ext_dir}.{filename[:-3]}")
self.logger.info(f"Loaded extension {filename[:-3]}")
except commands.ExtensionError:
self.logger.error(f"Failed to load extension {filename[:-3]}\n{traceback.format_exc()}")
in ur main bot class
the setup function is fetched and used to load the cog
and call it in setup_hook
It came from the exact code I wrote:
await channel.send(json.loads(response.text)['content'])
I'm just copying from the YouTube tutorial as I've never done much stuff before but it worked perfectly fine for the guy so a little puzzled haha
no i meant where are u getting this response variable from
are u requesting some data from an api?
Oh, my bad.
Yep, I'm using an API https://rapidapi.com/LemmoTresto/api/joke3
Succes when loading the cog and syncing but still cannot see the command.
No error messages either.
import requests
url = "https://joke3.p.rapidapi.com/v1/joke"
headers = {
"X-RapidAPI-Key": "SIGN-UP-FOR-KEY",
"X-RapidAPI-Host": "joke3.p.rapidapi.com"
}
response = requests.get(url, headers=headers)
print(response.json())
try this
u have the rapid api key right
Think I setup the command wrong possibly but can't see anything obviously wrong.
So I need my bot to display a lot of items and pictures like these. How can i actually do that?
@shrewd apex Should i first do that or first make the commands?
make a simple ping command to test try reloading discord once if it doesn't show up
Thanks, but I get the same errors sadly
But I did use await channel.send(response.json()) as it's meant to send a joke to a channel
print(response.status, response.content)
i think its likely the request fails
embeds
and markdown
Thank you but the same errors occur and if I remove the previous line of code and replace it with that the erros stop but they say "response object has not attribute status"
just print (response.content)
i think its response.status_code tho does ur idr not autocomplete?
Same errors for some reason
wdym sorry?
can u show what is printed in the console
like when u use . and type something do u not get a popup list on suggestions?
Oh yeah. But what if I want to send an emoji after a sentence
When I type it after response nothing comes up, no
Sure
Traceback (most recent call last):
File "C:\Users\deanb\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\requests\models.py", line 971, in json
return complexjson.loads(self.text, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\json_init_.py", line 346, in loads
return _default_decoder.decode(s)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1776.0_x64__qbz5n2kfra8p0\Lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\deanb\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\deanb\Downloads\Discord Bot\discordbot", line 55, in on_member_join
await channel.send(response.json())
^^^^^^^^^^^^^^^
File "C:\Users\deanb\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\requests\models.py", line 975, in json
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The response's content is empty 
What does that mean, please? I'm a noobie 
It means that you cannot get the JSON data from the response, since its content is empty
oh, i see
thank you
!d discord
@slate swan Hello, can you help me for vbox7 system?
async def vbox7_stream(ctx, video_url):
loading_embed = discord.Embed(title='Изчакайте докато видеото зареди...', color=0xFFD700)
loading_message = await ctx.send(embed=loading_embed)
vbox7_embed = await get_vbox7_embed(video_url, ctx)
await loading_message.edit(embed=vbox7_embed)
async def get_vbox7_embed(video_url, ctx):
vbox7_embed = discord.Embed()
vbox7_embed.title = 'Vbox7 Live Stream'
try:
response = requests.get(video_url)
soup = BeautifulSoup(response.text, 'html.parser')
# Print the entire HTML to the console for inspection
print(soup.prettify())
# Check if the meta tag is found
meta_tag = soup.find('meta', attrs={'property': 'og:video'})
if meta_tag:
video_id = meta_tag.get('content')
vbox7_embed.set_image(url=f'https://vbox7.com/play:{video_id}')
vbox7_embed.description = f'Видео: {video_url}'
# Simulate sending the video to Discord
await send_video_to_discord(video_url, ctx)
else:
raise ValueError("Meta tag 'og:video' not found on the page.")
except Exception as e:
vbox7_embed.title = 'Грешка'
vbox7_embed.description = f'Неуспешно извличане на данни от Vbox7: {str(e)}'
return vbox7_embed
async def send_video_to_discord(video_url, ctx):
# Placeholder for sending the video to Discord
# In practice, you may need to download the video and send it as a file
# Example using a placeholder file path, adjust it based on your actual implementation
file_path = 'path_to_video.mp4'
await ctx.send(file=discord.File(file_path))```
Hi! I want to transfer from discord.py to disnake. This shows up when i try to uninstall it
u installed dpy in the venv
ook
u can either activate the venv and uninstall it or delete the venv and create a new one
?
Why is this happening? Im using Disnake btw
i am gonna be honest u should probably learn some python switching libs wont help at all even rn the current issue is u didnt do pip install python-dotenv
i did
are u sure u have selected the correct interpreter
in vscode u seem to now be installing packages in global environment
ohh i need tchange the environment
yh could you walk me through it?
i am busy sorry
is it possible to select multiple values for the input value:
async def channels(interaction: discord.Interaction, mode: discord.app_commands.Choice[str], input: discord.TextChannel):
on my server i can only select one
does someone know?
not in slash commands
its possible for channel select iirc
is there any good alternative
class discord.ui.ChannelSelect(*, custom_id=..., channel_types=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current channels in the guild.
Please note that if you use this in a private message with a user, no channels will be displayed to the user.
New in version 2.1.
Question, im like 100% this is not possible, but wanna make sure.
So the role when a bot joins the server is that bots role. You can't delete it or give it to anyone else. Only time it goes away is if the bot leaves or is kicked.
Now when a bot joins the server, is there a way to make that role be a different color? like soon as the bot joins?
Or would this not be possible because of how discord does roles? Or maybe discord did a special way of bots being able to edit their own role? But im pretty sure its not possible but thats why I am asking.
!d discord.Guild.self_role
property self_role```
Gets the role associated with this client’s user, if any.
New in version 1.6.
So you would just make the bot edit the role?
yeah
Is that possible?
Cuz its the bots role... so the role hierarchy that discord does... i didnt think you could do that..?
Unless bots can just bypass that?
oh i see what you mean
yeah
But im wanting the bot to do it
when it joins a server.
change its own role, which normal user accounts cant do that? the role they have they cant edit they can only edit roles below them?
you would have to do some testing, i'm not 100% sure if discord treats it too differently
I will test it right now.
i doubt it will work tho
that would just be the event on_guild_join right?
right
okay.
"Bot does not have permission to edit roles in Testing?"
yeah. Its not gonna work sadly
The bot was given admin on join, so i dont think its possible.
Well that kinda sucks, would be cool if they could :/
unfortunate
Yep
only if discord allowed bots to edit their own role you know
that would be cool
But had limits to it... like only the color or something, not like perms n other stuff
Issue with that is that people would abuse it.
How so?
if you can only change the color or name of the role you cant really abuse that lol
Bot owners wouldnt abuse that power imma be real
Rainbow colors that sort of stuff. But you can already do that so it doesn't quite matter but still.
That would be way to many API request, and like i said, it would only be when the bot joins.
after they bot joins, they cant change it, they only get 1 change, after that then the owner can change it or admin
The only thing I want is slash command content regex matching for correct input and custom error messages ;-;
I meant like before invoking the command.
Like this
Plus the content regex to let the used know what hey did wrong.
No?
How so?
Mee6 does it, carl, dyno
Personally i dont do it because mine are all options or just common sense.
Example?
I can read JS it's fine just need prove that it can work lol
Then I will go to the dark depths of the raw API to do it.
yeah it doesnt look like they provide any kind of client-side validation beyond the type and min/max_value/length
if it did exist you'd most likely find it here https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-structure
Hmm this could be it https://discord.com/developers/docs/reference#error-messages
oh thats just API error messages, not the red text you're looking for
[2023-11-25 20:11:59] [ERROR ] discord.ui.view: Ignoring exception in view <ApprovalView timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\admin\Desktop\The-MP\cogs\whitelist.py", line 29, in approve_button
await interaction.response.send_message(f'Whitelist request approved for {self.user_id}.', ephemeral=True)
AttributeError: 'Button' object has no attribute 'response'
[2023-11-25 20:11:59,365] ERROR: Ignoring exception in view <ApprovalView timeout=180.0 children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\admin\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\view.py", line 427, in _scheduled_task
await item.callback(interaction)
File "C:\Users\admin\Desktop\The-MP\cogs\whitelist.py", line 29, in approve_button
await interaction.response.send_message(f'Whitelist request approved for {self.user_id}.', ephemeral=True)
AttributeError: 'Button' object has no attribute 'response'
Error in my bot, assuming it is something to do with the response I am trying to make?
Honestly it would be so cool with the regex 'n stuff.. then it would finally feel like proper command integration.
Code?
i would guess you have your parameters ordered as (button, interaction) instead of (interaction, button)?
class ApprovalView(ui.View):
def __init__(self, user_id, gamertag):
super().__init__()
self.user_id = user_id
self.gamertag = gamertag
self.counter = 0
@ui.button(label='Approve', style=discord.ButtonStyle.green)
async def approve_button(self, button: ui.Button, interaction: discord.Interaction) -> None:
self.counter += 1
if self.counter >= 1: # Set the number of clicks required for approval
conn = sqlite3.connect("rmc.db")
cur = conn.cursor()
cur.execute("UPDATE user_data SET game_name = ? WHERE discord_id = ?", (self.gamertag, self.user_id))
cur.execute("UPDATE user_data SET whitelisted = 1 WHERE discord_id = ?", (self.user_id,))
conn.commit()
conn.close()
database[self.user_id] = self.gamertag
await interaction.response.send_message(f'Whitelist request approved for {self.user_id}.', ephemeral=True)
self.stop()
else:
await interaction.response.send_message(f'Approval count: {self.counter}', ephemeral=True)
Ye
Can you explain why that would cause an error? (Just curious)
Because that button object doesn't have the same attributes and functions as the interaction object.
dpy calls your function using positional arguments, so if you don't have them in the same order, you're going to have those arguments assigned to the wrong parameters
Ah, I understand, thank you both
have fun :)
I don't know why I engaged in this...
shut yo goofy ass up
i know metolix
he does sadly ||help he harrases me, also sorry for off topic convo here||
It's okay, it's #discord-bots, known for OT and.. barely legal conversations about coding.
Please stay on topic ma'am...
Do not assume my gender bro am not LB barbe q
Mods, ban em
Get em outta here!
no u
it's interaction.response correct?
uhh correct as in its a thing that exists
lol
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
i've been using defer for so long that I forgot how to do a standard response xD
!d discord.InteractionResponse.require_premium
await require_premium()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the user prompting them that a premium purchase is required for this interaction.
This type of response is only available for applications that have a premium SKU set up.
wtf when was this a method
lol
well anyway .send_message() is what you'd want
It's new
I'm updating a silly discord bot.
I think at least
and the horrors. Original author is using a json file as a database that's constantly opening and closing ;-;
ah i didnt realize the bot used latest docs instead of stable
Honestly I feel like that's something they should look into
Did you hear me?! HE'S USING A JSON FILE AS A DATABASE ;-;
Sometimes using the master branch is a bit misleading as most users use the stable
are you enjoying the technical debt? 🥴
what im going to enjoy is when I finish updating this damn bot, releasing it publicly to publicly shame the original author who actually demanded money for this nonsense and stopped maintaining it
i also assume it's not linted, unformatted and is a 800 line main.py file
what the hell?
he's using the interactions package
which idk if that even works anymore
so I have to migrate it all to discordpy lol
with open('configs/lfg_config.json', 'w') as f:
json.dump(d, f, indent=4)
why are they prettifying it
oh god no
d['black_listed_players'].append(int(discord_id))
they put an UNDERSCORE between blacklisted?????
Anyway, here's my remade version.
I cbf making a proper database lol
https://paste.pythondiscord.com/SCOQ
def __init__(self, client):
print("[Cog] LFGMonitor has been initiated")
self.client = client
with open("configs/json/lfg_config.json", "r") as f:
config_options = json.load(f)
f.close()
roles = config.lfg_blacklist_command_perms
ermmm
wot
i assume you meant to put it inside the init function, not outside, right?

