#discord-bots
1 messages ยท Page 255 of 1
none
r = redis.Redis
cant show you rest
it gives a channel id
having a better name wouldn't be a bad idea
Again, int or string
do i put it in string
ahh
Channel IDs are integers
oh
but i turn the channel into an id
Then use something like
channel1 = client.get_channel(...) or await client.fetch_channel(...)
It first tries to get it from cache, if it's not found and returns None it will make the API call with fetch
im using that
No you're not
And? Where's the second part?
channel
I told you to use
channel1 = client.get_channel(...) or await client.fetch_channel(...)
Do you see that anywhere in your line? No.
The entire thing is a line
wait
You don't choose between get_channel or fetch_channel
You write them both with an or operation in the middle
!e ```py
print(None or "something")
print("something" or "other something")
print("something" or None)
print(None or None)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | something
002 | something
003 | something
004 | None
if the first thing is not truthy it will get the other thing instead
we try to get channel from the cache but if its not here we fetch api
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "/Users/zagzag/vscode/zagzag.py", line 500, in verify_setup
channel1 = client.get_channel(channel) or await client.fetch_channel(channel)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 2565, in fetch_channel
data = await self.http.get_channel(channel_id)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In channel_id: Value "b'1112053260879147133'" is not snowflake.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'verify-setup' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In channel_id: Value "b'1112053260879147133'" is not snowflake.```
what is a snowflake supposed to be
in my code?
where else?
oh ok
Is python the best language for discord bots
for me yes
its easier than js
r.set(f"vchannelid {str(interaction.guild.id)}", int(verify_channel.id)) is this how you do it?
no idea how redis stores values
You get bytes back so decode them and convert to int when you get the channel ID
!e
x = b"123456789"
print(int(x.decode("utf-8")))
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
123456789
Many people use some unknown language
I donโt remember the name
lua is known
Itโs not used by many
https://discord.com/developers/docs/topics/community-resources#libraries-discord-libraries
here are all libraries that have valid rate limit implementations
ruby?
Many people use some unknown language
Then you're contradicting yourself
Oh
Language is still Python
hikari is python library but for sure not for begginers
Yea i know
Heard about Hata
!pypi Hata
tf is that
https://github.com/HuyaneMatsu/hata
Their example code is a bit wacky though
Seija = Client('TOKEN', extensions = ['slash'])
You don't name variables with an uppercase
Oh
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/zagzag/vscode/zagzag.py", line 619, in on_message
channelv2 = int(channelv.decode("utf-8"))
AttributeError: 'NoneType' object has no attribute 'decode'
channelv is None
ok
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/zagzag/vscode/zagzag.py", line 141, in on_member_join
await channel.send(message.format(mention=member.mention))
AttributeError: 'bytes' object has no attribute 'format'```
you need to decode it
@client.event
async def on_member_join(member):
try:
channel1 = r.get(f"channelid {str(member.guild.id)}")
channel2 = int(channel1.decode("utf-8"))
channel = client.get_channel(channel2) or await client.fetch_channel(channel2)
message = r.get(f"message {str(member.guild.id)}")
await channel.send(message.format(mention=member.mention))
except KeyError:
pass```
i have
look
yes still the same answer you need to decode it
wdym
redis always returns bytes
it is decoded
where is message decoded
cause its bytes?
it doesnt matter everything must be
if its int you need to cast it into int
should i decode it to string?
no it will be string already
but its supposed to be a string
so it will be
there is
so if i decode it to a int then it will still be an string
but i aint explaining that
!pypi aioredis
so if i decode it to a int then it will still be an string
there's a PEP
you are not decoding it to any types you just decode it
oh ok
!pep 3156
well not sure if it explains that
TypeError: object NoneType can't be used in 'await' expression
show code
and full traceback
Traceback (most recent call last):
File "C:\Users\chain\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\chain\Desktop\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Soul Client #1\Server Backup\bot.py", line 42, in on_ready
await register_cogs_async()
File "C:\Users\chain\Desktop\Recover_Cord (1)\Recover Cord\PRIVATE BOTS\Soul Client #1\Server Backup\bot.py", line 37, in register_cogs_async
await client.add_cog(Commands(client))
TypeError: object NoneType can't be used in 'await' expression
Code:
async def register_cogs_async():
"""Register cogs for the bot asynchronously."""
await client.add_cog(Commands(client))
and where do you call this
Code:
async def register_cogs_async():
"""Register cogs for the bot asynchronously."""
await client.add_cog(Commands(client))
yes, still the same question
wym
where do you call register_cogs_async
async def register_cogs_async():
"""Register cogs for the bot asynchronously."""
await client.add_cog(Commands(client))
@client.event
async def on_ready():
await register_cogs_async()
do you use discord.py?
yes
and may i know why you load cogs this way and not using setup function?
like this
Hey there ๐ Iโm looking for a solution, last step for the connection with discord
What python version is that
is there a way to send a message that mentions a user and a embed at the same time with on_member_join
Just do it in the event
3.10
await channel.send(member.mention, embed=embed)
Where:
channelis a subclass of typediscord.abc.Messageable, represeting the channel you want to send the message tomember, an instance ofdiscord.Memberrepresenting the user you want to mention (assuming this is in anon_member_joinevent, it'll probably be the newly-joined member)embed, an instance ofdiscord.Embedrepresenting the embed you wish to send in the message
thanks
I have seriously tried a lot of things so Iโm very curious what might be the problem ๐ค
I'd say the problem is coding on phone :p
You didn't get errors when installing the library?
Try to reinstall the library. Seems that one of the depencies is not installed correctly.
I see people have the same issue with pyto, so i guess it's actually the pyto problem
https://www.reddit.com/r/Pyto/comments/135ug6w/pyto_invalid_module_help/
What's the correct way to get the reacted emoji name when using
def check(channelID, user, emoji):
if channelID == context.channel.id:
if user == "everyone":
return True
elif int(user) == context.author.id:
return True
bot.wait_for(..., check=check)
I don't know how I'd get the reactions
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.11)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.11)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.11)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
there is an example with reaction
line 9, in <module>
@bot.event()
^^^^^^^^^^^
TypeError: Client.event() missing 1 required positional argument: 'coro'
Error^
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=',', intents=intents)
@bot.event()
async def on_ready():
print('{0.user} is online')
@bot.command()
async def discord(ctx):
await ctx.send('')
bot.run('')
Code^
event doesn't need the brackets at end
@bot.event
thanks so much
Is having your bot as phone status against TOS?
No
It's just putting for example Discord Android in the identify payload when you connect to the gateway, which isn't what should be done as per documentation, but Discord showing the status for bots is their problem
Discord's documentation wants you to put the library's name in the connection properties of the identification payload
If you don't put that but something else, it's not a big deal just not want Discord wants - but not against ToS
You didn't ask any questions
Not if you just send some random picture with no context
Just ask your questions here if you can't send pictures wherever you want to send pictures
have to huh
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Why do you do ctx.author.user.name
author is already a user
And it's avatar.url not avatar_url
Thanks for the reaction, Iโll try ๐ฌ
How do you make a cog do something every time its loaded?
Why Errol?
Look i did but he said an error
You need to import asyncio obviously
Work in slash command?
Slash commands have nothing to do with that
You can import whatever you want whenever you want in any python file, as long as it's installed
Only prefix?
Just. Do. It
Yes i know
Then you know your question doesn't make sense
And if you sleep 10 seconds, you'll need to defer
But I didn't know that there is an asyncio import
That's what I told you minutes before you sent that question
You even responded to that message asking if using import works in slash commands
Which, as mentioned, doesn't make sense
Yes ty
No i mean After time sleep Slash command working?
^
And again, it's not time.sleep but asyncio.sleep
Yes i forget ๐
๐ฟ๐ฟ
anyone can help?
output
source
from discord.ext import commands
import os
import asyncio
import datetime
client = commands.Bot(command_prefix=".", intents=discord.Intents.all())
col = discord.Color.from_rgb(3, 240, 252)
feedback = 1121065558121656372
@client.event
async def on_ready():
print("Success: bot is connected to Discord")
class SuggestModal(discord.ui.Modal, title="Send a suggest"):
sg = discord.ui.TextInput(label="Send us your suggest", placeholder="eg. add minigame", required=True, min_length=20, max_length=2000, style=discord.TextStyle.paragraph)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f"{interaction.user.mention} Thank you for submitting your suggest, the moderation team will see it momentarily!", ephemeral=True)
channel = client.get_channel(feedback)
embed = discord.Embed(
title="Suggest from member",
color=col,
timestamp=datetime.datetime.now()
)
embed.add_field(name="User name:", value={interaction.user.name}-{interaction.user.discriminator})
embed.add_field(name="Suggest:", value={self.sg}, inline=False)
embed.set_thumbnail(url=interaction.user.avatar)
await channel.send(f"<@&1100415432567033916> New feedback, check it!", embed=embed)
@client.tree.command(name="suggest",description="Send a suggest to server")
async def suggest(interaction: discord.Interaction):
await interaction.response.send_modal(SuggestModal())```
embed.add_field(name="User name:", value={interaction.user.name}-{interaction.user.discriminator})
Unsure why you are subtracting the discriminator from the username
embed.add_field(name="Suggest:", value={self.sg}, inline=False)
You are setting the value to be the TextInput object rather than the value of it - self.sg.value
thanks a lot, fixed
have you coded that?
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
And that looks very AI generated weird code
YOUR_INSTAGRAM_USERNAME ๐
So you broke 2 rules - 5 and 10
!rule 10
10. Do not copy and paste answers from ChatGPT or similar AI tools.
:x: Invalid rule indices: 55
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.

Copy and paste answers 
2. Follow the Discord Community Guidelines and Terms of Service.
!rules
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
Yeah it's not a channel to get all rules sent
you need to follow all of them not just 1
apparently not
!d nextcord.ext.commands.Bot
class nextcord.ext.commands.Bot(command_prefix=(), help_command=..., description=None, *, max_messages=1000, connector=None, proxy=None, proxy_auth=None, shard_id=None, ...)```
Represents a discord bot.
This class is a subclass of [`nextcord.Client`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Client "nextcord.Client") and as a result anything that you can do with a [`nextcord.Client`](https://nextcord.readthedocs.io/en/latest/api.html#nextcord.Client "nextcord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://nextcord.readthedocs.io/en/latest/ext/commands/api.html#nextcord.ext.commands.GroupMixin "nextcord.ext.commands.GroupMixin") to provide the functionality to manage commands.
there is something like delete_after
Its embed? You mean only the embed or the message?
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
delete_after kwarg
delete_after (float) โ If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
What object do you think that's from
it will delete whole message it just sent
!d discord.Message.delete
yeah
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
Your own messages could be deleted without any proper permissions. However to delete other peopleโs messages, you must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages").
Changed in version 1.1: Added the new `delay` keyword-only parameter.
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is โsyntheticโ and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
(There's docs for a reason)
you can set delay for deleting message as well here
no
the delete method wont just appear out of nowhere you need to run it at message object you want to delete
and the delay is a keyword argument
so you cant just do msg.delete(5) it has to be msg.delete(delay=5)
and your own message with command you ran you can find out in the ctx.message as the docs say:
The message that triggered the command being executed.
can someone help me make a discord bot? for antinuke
And that try/except is a bit weird and pointless
You made the member argument required
How to block some people from using a discord bot command and blocking some inputs for commands [ the usernames and inputs should be editable without edditing bot code]
if you dont provide member it will throw exception
i think i can use pastebin for usernames and inputs [ most likely ]
So, the member arg will never be None
if you want it to be optional set None as default value
x: type = default
member: discord.Member | None = None
You know, it's better to know basic Python before trying discord.py
They've been told that lots of times but don't care a tiny bit 
also there is a trick in python and you can use it like this:
member = member or ctx.author
``` which means member will be provided member and if its not provided ctx.author will be used instead

is there a way to retrieve the users of a forum channel?
is there any basic template / code for making discord slash commands
need help with this ^
check if the user has the role or not and change it depending on that
!d discord.Thread.members
property members```
A list of thread members in this thread.
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be properly filled. Most of the time however, this data is not provided by the gateway and a call to [`fetch_members()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread.fetch_members "discord.Thread.fetch_members") is needed.
ุณูุงู
I asked for the members that are present in the central ForumChannel, not a thread
forum channel overall or a post
then its based on permissions
like, the people that are members of the #1035199133436354600 main channel, not its posts
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
there is an example
yes i understand you want to get list of Members who can see this forum channel
but its not as straight as accessing one attribute
if you want that you need to get list of all guild members
get their permissions and copare to desired channel
I do know that. I was hoping I'd save using "for" loops or similar methods
yeah i dont know any other method apparently
in 20k+ servers that process can take some time
yeah
thanks for replying though. much appreciated
!rule 4
4. Use English to the best of your ability. Be polite if someone speaks English imperfectly.
in what language is the original discord API written in
i thought discord.py was official from, discord
no there is no official library from discord but there is a list of libraries that** have valid rate limit implementations, are recently maintained, and have large communities of active bots.**
https://discord.com/developers/docs/topics/community-resources#libraries-discord-libraries
bless those who started these SDKs
there's DSharpPlus
stg devs are the best at naming things
there's even one in rust
yeah but most of them are in python xd
yeah no kidding
I'm curious what makes python so dang popular, not only that, but how fast we come up (by we i mean the devs who put the work in) with whatever's needed to transport something so that it's python friendly
its insane
well python is just easy to operate
I think the biggest turnover will be the fact it doesn't have strict types.
And no forced public static protected bool
Hence the reason AI is a lot in Python since it doesn't matter how fast the code runs it still needs to process it with the GPU, so the code will not be the bottleneck so they chose the most convenient.
!cogs
!dcogs
question if my bot.py file is running my activity status only should i just change the name to activity.py
you will need to rephrase that
@client.tree.command(name='slayer')
@app_commands.describe(username = 'Whats your Minecraft username', slayer = 'What Slayer', level = 'What level u want to see')
@app_commands.choices(slayer=[
discord.app_commands.Choice(name= 'Voidgloom Seraph', value='Voidgloom'),
discord.app_commands.Choice(name= 'Sven PackMaster', value='Sven'),
discord.app_commands.Choice(name= 'Tarantula', value='Tarantula'),
discord.app_commands.Choice(name= 'Revenant Horror', value='Revenant'),
])
async def slayer(interaction: discord.Interaction, username: str, slayer: discord.app_commands.Choice[str], level: int):``` i dunno it says application didnt respond
You're not responding in that code block. In fact, your function does nothing - it's just decorators and a function definition
it has alot of code after it
!paste it then
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.
Can I ask you a question?
Don't know, can you?
can i get help with this error please?
manage_messages
what happen?
so what is?
https://paste.pythondiscord.com/ubotuyapit
Discord keeps saying "This interaction failed"
How ever, everything works, I don't know what I'm doing wrong
...........
oh i see sorry lol ty
Logs in console?
nothing
console does not throw out errors
@slate swan
for me to run my 3 files i would have to put them in a folder called cogs right?
Does your code to get the data from the API and handle it take longer than a few seconds? If yes, you need to defer
Do you have some error handler that eats every error? Like on_error or something like that
i made 1 more command using the same api and it works just fine
Pretty much yeah
this one with options doesnt work for a reason
Doesn't prove anything
Alright thank you
Defer it and see if it works afterwards
how do u defer
await interaction.response.defer() at the top
its stuck on thinking..
i think theres suum problem with code
cause the other one without options works fne
fine*
p intrestng why my code dont work
Add an else branch
See if it goes there
Add some debug logs with print and check the flow it goes through
try the if statement
wym
You only have if/elif
Add an else at the bottom and most importantly print logs a bit everywhere and see how your code goes
the entire code worked when i was using normal bot prefixes
and i made another command it also worked with /
but this command has Choices soo it doesnt work
do i need to like register them or enabling anything for them to work
You need to register the slash command that's it
lemme like edit code rq
Cool code?
And what is wrong with them?
Anyway Answer my problem
When I put it back 2 times
opens to
????
Doesn't make any sense, sorry
what
What you're saying doesn't make sense
Bruh
And remove the code that produces the second picture
Rewrite your code so that it produces the same as the first picture again

And otherwise without code it's hard to understand what you're doing and what is wrong as your English is not the best
When I use a command that repeats itself
Creates an embed add file
Check photos
without code it's hard to understand
Dude stop spamming your pictures and give your code for once jeez
SEND. THE. CODE.
But if I don't, it won't work
!paste your entire command code there
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.
@slate swanhow to get the user id of the person who used a / command
interaction.user.id
Or ctx
Not for slash commands, no
Interesting that people always keep using good names ctx, inter/interaction even if they don't know python at all and their other variables are just random things. Never seen someone who uses another name
Because people have seen it too many times
they search "how to make a discord command with python" and then continue themselves
"discord bot with 300 commands code download free" ๐
yup
or they get it from chatgpt
But then they have lots of comments
@slate swan sorry for the late response.
I have fixed the issue, can you answer me that?
https://paste.pythondiscord.com/oduxicaxit
I want the button to change the color from blue to green on interaction,
I also want the dropdown to change to green on interaction, how do I do that?
I don't understand how to do this with the Ranked Card. I have already watched a video (Video Link: https://youtu.be/3ktorz8QJTM), but I just can not figure out how I can do this best and understand. The command works, but I would like that when you enter /rank, that your data is displayed on a banner.
Current levelingcode: https://sourceb.in/7rkalJhyw5
Would be happy if someone would help me to understand it
Code And Images - https://github.com/AdvicSaha443/Discord.py-Leveling-System-Bot.git
Easy-pil - https://github.com/shahriyardx/easy-pil.git
Check Out Some of my other videos:
โ Youtube Notification Bot - https://www.youtube.com/watch?v=qZ6kcQJxbzQ
โ Reaction Role Bot - https://www.youtube.com/watch?v=kmLbp8CBkm0
Music:
โบ Music Credit: LAKEY I...
Disnake.py easy
you answered something not related to the question
do you know how to use pillow?
Yeah, but not for the bar
maybe show us the issue you are having
exceptions and code
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name} ({bot.user.id})")
print("Bot is ready")
for cmd_file in setting.CMDS_DIR.glob('*.py'):
if cmd_file.name != '__init__.py':
await bot.load_extension(f"cogs.{cmd_file.name[:-3]}")
thsi is the code
i am folling a tut for it
my files to verify that its not locaiton error
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.Start_comm' raised an error: TypeError: object NoneType can't be used in 'await' expression
this is the error
can you print what cmd_file.name is?
Start_comm.py
u mean to print in code?
ah ya so u mean to replace await stuff with print ?
no i did not say to replace it
i just want to know whats under this varriable
whats so hard in doing print(cmd_file.name)
thats waht i was saying to do
no you said to replace it with await
i want you to put it above it
and show me what it prints
yes, can be
you can't order me what to do!
๐ญ
anyone have any idea how one of these would be made where it updates itself in time of using a command to add and remove people from the q
just use some buttons
ok show the code of this file
from discord.ext import commands
# Create a new cog class
class StartComm(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Command to start the bot
@commands.command()
async def start(self, ctx):
await ctx.send("Bot is ready!")
# Setup function to add the cog to the bot
def setup(bot):
bot.add_cog(StartComm(bot))
The issue is in that start_comm file
ok imagine the bar occupies 150px it starts at x = 100 and ends at x = 250
then, you'd need to calculate which % of the level is completed, for example, you have 20xp and need 100xp, so you're 20%.
Now you get the 20% of 150, it's 30, then you just make a rectangle (making it easy) that starts from x = 100 to x = 130
setup function must be async
and .add_cog must be awaited as well
ohhkee
misson succesful
@slate swan btw remeber code i showd u yesterdday in 3 files
i am planning to put it in this one start_command file
what u think good idea?
may be
How do I write that into my code ?
if you find hard to do that, I would recommend following with your discord bot and when you get a better level come back to this
!code
you've been asked to share your code countless times
if you don't provide code we wont be able to help :)
Hello please help me but I won't share my code
Edit:
Hello please help me, these are a few random lines from my code but not everything because I don't want to
It's hard to help when someone doesn't read at all
You've been told countless times to share the ENTIRE code of your command
this guy is nuts
So maybe it's time to share the ENTIRE code for once
Maybe with this bold and underline style it'll be easier
for what are the code blocks lmfao
proceeds to delete every message in existance
await member.add_roles(role)```
it said theres an error in the member file of python discord
when the role gets added can someone help me fix
What error?
- role = discord.utils.get(member.guild.roles, id='1121191878063308821')
+ role = member.guild.get_role(1121191878063308821)
idk it was saying there was an error of the member.py file of python discord
line 1044 i think
Do you know how to make a a code that auto react to all new messages in a chat
yes
No but I can show you how to
mmhm
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your botโs own messages and private messages are sent through this event. This can lead cases of โrecursionโ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji").
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. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions "discord.Permissions.add_reactions") is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
That's all you should need
discord.py is an advanced library so I'd recommend getting comfortable with Python first
Oh ok
I already did a auto send message bot
And auto send and delete at the same second for that servers that have level
@client.event
async def on_message(message):
emoji = ':thumbsup:' # Emoji
target_channel_id = 343944376055103488 # Channel ID
if message.author == client.user:
return
if message.channel.id == target_channel_id:
await message.add_reaction(emoji)```
Thatโs it?
Try it and see
No problem
becaues it's inside an embed
Pings only work outside of embeds
How do i add a command to my bots profile like this
I already have the slash command I want to add but I don't know how to make it show up on the profile
I think that's a feature of verified bots
It's automatically done for verified bots, nothing you can control
i tried to run my discord bot on www.pythonanywhere.com and got this error
discord module is installed so idk whats wrong can someone help
The issue is pythonanywhere and a free account
You'll find similar issues when searching on Google https://stackoverflow.com/questions/63347818/aiohttp-client-exceptions-clientconnectorerror-cannot-connect-to-host-stackover
here is my code:
import asyncio
from aiohttp import ClientSession
async def main():
url = "https://stackoverflow.com/"
async with ClientSession() as session:
async with
just install Python on your device (or VPS) and you'll probably not have the issue anymore
the point is im not trying to run it on my pc
im trying to host a discord bot in the cloud
not trying to pay for one
You'll struggle then, most free hosting services come with some sort of catch
I'm currently with DigitalOcean and they've been great for me
is it free?
i just need something free and 24/7 it can be trash idc
as long as it works im fine with it
nvm i already tried them
they make u link a payment method when u sign up
It's a paid service. But they'll probably offer some sort of free trial if you want a taster
im literally just making an order bot for a minecraft city roleplay server
where players can order items
so i dont really wanna spend money
Most VPS providers have some sort of free plans with limitations, look at then
im seeing if aws has it for free rn
why does oracle make the shadiest looking programs bruh
You'll get banned when using Oracle's free plan
For hosting a Discord bot? Why?
Ask people who tried it, they ban without notice nor reason(s)
You get banned for other things as well that are less resource eating than Discord bots
Forum posts, reddit posts, blog posts, ... you'll find countless people having such experience with Oracle
Though try it and see after some day(s) what happens 
Then make attempts at contacting their support, they will ghost you 
That sounds odd, but I've never used them. My reasonable expectation was that they say "Here's this free thing. Here are the CPU, memory, networking, and storage limits. We don't care what you run, just don't exceed those limits."
Well, don't care within reason. Don't host some malware or whatever.
Well that's what most people initially thought I guess
Until they got banned with no reason for hosting some harmless Discord bot or other thing
discord bot newbie here - I see from the docs that I could use a Client or a Bot instance? How would I go about deciding which might be the better choice?
Bot is a subclass of client, so it's got everything client has with more features (like command handling)
If you just want a really simple script that doesn't handle commands or anything, Client.
Otherwise bot. You probably want bot anyway
Ah! That was not obvious!! Thank you.
I found some replit method with a web server that allows me to host it 24/7
is that reliable it uses uptimebot to ping the webserver every 5 minutes
and it keeps the bot alive
Definitely not
Replit is not a hosting service
See the pinned message in #965291480992321536 for some actual hosting options
Right up until it doesn't
its a super small bot with a welcome message and autorole
for a small server so i think it will be fine
What do people use for having various dev and testing versions of a bot? Create separate discord servers to invite those into? Use some sort of prefix on every command except production? Something else?
Different bot in a testing server
Usually different bot in a different server
Or in the same server with a different prefix
Thanks again
guys i cant see a icon of embed. anyone have same issue with me or they updated to delete icon?
Hi, i need help please for send error in channel with webhook
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/otrobot.py", line 256, in delete_verification
await interaction.followup.send(embed=embed_error)
File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1800, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'delete_verification' raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
Author icon?
yes yes
Known issue, Discord is aware
if ur using slash command u can have production bot commands synced globally and dev bot only for ur server
Perfectly timed!! That's exactly what I'm reading about and wondering...
ohhhh thank you! i thought my PC issue
possibly even set up permissions and roles checks for ur commands
If you post there and 5 minutes later ask here, why not just ask here directly
please
Its my command:
@bot.tree.command(name = "delete_verification", description = "Delete verification and channel")
async def delete_verification(interaction, role_id : discord.Role):
guild_id = interaction.guild.id
guild = interaction.guild
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
try:
if database_verif.get_role_id(guild_id) is not None:
database_verif.remove_verification(guild_id, role_id.id)
if database_verif.get_role_id(guild_id) is None:
channel = discord.utils.get(guild.text_channels, name="verification")
await channel.delete()
await interaction.response.send_message("The verification is removed successfully")
else:
await interaction.response.send_message("Error deleting verification")
else:
await interaction.response.send_message("The verification is not in place")
except Exception as e:
embed_error = discord.Embed(title="Error", description=f"{e}")
await interaction.followup.send(embed=embed_error)
webhook = "LINK_WEBHOOK"
data = {
"content": "@everyone",
"embeds": [{
"title": f"Error disable_verification on {interaction.guild.name}",
"description": f"{e}",
"color": 16732345,
"footer": {
"text": "OtroBot"
},
"image": {
"url": "https://i0.wp.com/xboxera.com/wp-content/uploads/2020/08/XGPgamescom_inline1.jpg"
}
}],
"username": "Log Error OtroBot",
"avatar_url": "https://i.imgur.com/44N46up.gif"
}
requests.post(webhook, json=data)```
First time i have error with webhook
I did it and it won't get better
ctx.send
And you need message content intent for prefix commands
or ctx.reply
!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.
Krypton you know why Unknow webhook ?
You should know though with all the commands that "you" made working
E.g. that command you've spammed with pictures and never shared code
Webhook is unknown
Yes but he is defined
No
await interaction.followup.send(embed=embed_error)
You can't send a followup if you've never responded in the first place
So do like you did in your entire code, await interaction.response.send_message(embed=embed_error)
lottery_message = await interaction.message.channel.fetch_message(message_id)
this is not working
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
message-id is correct
Ok work thanks
Why not use interaction.channel directly
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, if sent from a DM channel recipient is None.
And the message should be in that channel obviously
no my message is in other channel
Then it won't work
then what shall i do?
get the channel object for the channel the message is in
fetch the message there
fetch channel? and then fetch message?
ok
Get channel, if it returns None then fetch channel
Then fetch message
Hard to help without the code
await ctx.send(title='', description='**:tick_red: | I Do not Have Ban Members Permission To Perform This Command**', color=0xe74c3c)
What is that
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
There are no title, description and color arguments in the ctx.send method
is possible to get member instance from the id ?
!d discord.Guild.get_member
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
you are a live saver
thanks
btw is the "/" a second parameter ?
No, it's there to tell Python that the arguments in front of it should be positional-only
oh ok thx
also may ask another question ? is user.discriminator property still working even after the username update ?
i see, thx
can you change message send perms with discord.py?
yeah
!d discord.Role.edit
await edit(*, name=..., permissions=..., colour=..., color=..., hoist=..., display_icon=..., mentionable=..., position=..., reason=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the role.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this.
All fields are optional.
Changed in version 1.4: Can now pass `int` to `colour` keyword-only parameter.
Changed in version 2.0: Edits are no longer in-place, the newly edited role is returned instead...
change permissions
but like of a channel
i am trying to make a black jack bot
then do the same but with channel
!d discord.TextChannel.edit
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 1.4: The `type` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead...
ily
!d discord.TextChannel.set_permissions
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
what is asynciterator ?
do you know what an iterator is?
Iterator that's asynchronous
i believe its lists tuples sets etc
no
something that you can do a for loop in
those are iterables
!e
print(iter([]))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
<list_iterator object at 0x7f4332604790>
list and list_iterator are different things
!e it's like async generator but iterator
import asyncio
async def async_gen() -> None:
for i in range(10):
yield i
async def main() -> None:
gen = async_gen()
print(gen)
print(*(i async for i in gen))
asyncio.run(main())
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | <async_generator object async_gen at 0x7f18b2f14790>
002 | Traceback (most recent call last):
003 | File "/home/main.py", line 13, in <module>
004 | asyncio.run(main())
005 | File "/usr/local/lib/python3.11/asyncio/runners.py", line 190, in run
006 | return runner.run(main)
007 | ^^^^^^^^^^^^^^^^
008 | File "/usr/local/lib/python3.11/asyncio/runners.py", line 118, in run
009 | return self._loop.run_until_complete(task)
010 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
011 | File "/usr/local/lib/python3.11/asyncio/base_events.py", line 653, in run_until_complete
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/wujoloyine.txt?noredirect
Sounds about right
!e
import asyncio
async def async_gen() -> None:
for i in range(10):
yield i
async def main() -> None:
gen = async_gen()
print(gen)
print(*[i async for i in gen])
asyncio.run(main())```
@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | <async_generator object async_gen at 0x7fbba0134790>
002 | 0 1 2 3 4 5 6 7 8 9
() doesnt make it a tuple im afaik
It's for generator expressions
wdym
!e
print((i for i in range(10)))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
<generator object <genexpr> at 0x7f7df86e01e0>
Yes?
@thin raft :white_check_mark: Your 3.11 eval job has completed with return code 0.
0 1 2 3 4 5 6 7 8 9
im confused, why did it raise an error in the first code?
i think i need understand how asynchronous programming works
Probably because it's using async for
i still dont understand it
So it turns into async generator
thank you guys for the help
well, sorry im asking a lor but, what is the diffirence between .guild and .Guild
discord.guild is a module, discord.Guild is a class
when i did ctx.Guild it said Guld is not an attribute of ctx
Eh, I thought you asked about discord.guild and discord.Guild stuff
!d discord.ext.commands.Context.guild
Returns the guild associated with this contextโs command. None if not available.
Well, the error is right
You can use list comprehension to collect them, the flatten method was removed
What api
oh
thanks ;-;
@naive briarbut can you consider Asynchronous Iterator as a list or something
how can i get the data inside it
!list-comp
Do you ever find yourself writing something like this?
>>> squares = []
>>> for n in range(5):
... squares.append(n ** 2)
[0, 1, 4, 9, 16]
Using list comprehensions can make this both shorter and more readable. As a list comprehension, the same code would look like this:
>>> [n ** 2 for n in range(5)]
[0, 1, 4, 9, 16]
List comprehensions also get an if clause:
>>> [n ** 2 for n in range(5) if n % 2 == 0]
[0, 4, 16]
For more info, see this pythonforbeginners.com post.
Just change for in to async for in
i know how list comprehenion works, but idont howt o apply it to that class
thats it ?
and ban is a banentry right?
Yes
thanks a lot again ;-;
hey guys i am having some issue in imporitng a cog
in discord.py
can anyone help out pls
can ya mate?
instead of saying you have issue about something maybe send the actual error and code corresponding to the issue
i thought it was a good manner to ask if someone is free first
dont wana be like rude boss
no cause you are not asking 1 person
when someone is free they are gonna answer here
if you send just the text saying you have issue they are most likely going to ignore it or dont even notice it
show it
e:\onepiece-bot\main.py:26: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension('StartComm')
Object allocated at (most recent call last):
File "e:\onepiece-bot\main.py", lineno 26
bot.load_extension('StartComm')
ERROR - discord.client : Ignoring exception in on_ready
Traceback (most recent call last):
File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 947, in _load_from_module_spec
await setup(self)
File "e:\onepiece-bot\Cmds\start_comm.py", line 10, in setup
await bot.add_cog(start(bot))
File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 770, in add_cog
raise TypeError('cogs must derive from Cog')
TypeError: cogs must derive from Cog
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:\onepiece-bot\onepiece\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "e:\onepiece-bot\main.py", line 30, in on_ready
await bot.load_extension(f'Cmds.{cmd_file.name[:-3]}')
File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "E:\onepiece-bot\onepiece\lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'Cmds.start_comm' raised an error: TypeError: cogs must derive from Cog
E:\onepiece-bot\onepiece\lib\site-packages\discord\client.py:446: RuntimeWarning: coroutine 'Command.__call__' was never awaited
await self.on_error(event_name, *args, **kwargs)
Object allocated at (most recent call last):
File "e:\onepiece-bot\Cmds\start_comm.py", lineno 10
await bot.add_cog(start(bot))
from discord.ext import commands
@commands.command()
async def start(self, ctx):
await ctx.send("Hi, I am ready!")
async def setup(bot):
bot.add_cog(start(bot))
.add_cog as the name says is for adding cogs not commands
you cant just put random thing in it and expect it to work
there is something like .add_command but im not sure if this will work just create a cog and add this command into it
yes this should work
wait no
the Cog is uppercase
not lowercase
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
this may be useful
did you change the cog to Cog
can you show full code and traceback you are getting
bot.load_extension('StartComm')```
yeah it tells you the problem
you did not await the bot.load_extension
but the code never add it there
but it is there
do u think he will reply
if the error happens it means you did not
the error literally shows you the line why dont you go to this line and check it
yeah you still did not add it
commands file
its there
there literally is no await and i showed you before
add await before bot.load_extension
man can you read
there is a wait in commands .py see
read your error
which line is raising the error?
read my messages again and maybe you will see where i showed you line without await
line no 26
line 26
i should leave codding fr
got it sir sorryyy
Or just read errors duh
done
next time dont send errors when you see it occur just try to solve it and when you fail send it here
the error was line 26
send that traceback
The error was
RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
bot.load_extension('StartComm')
sorry got confused in file name too

i will just dont copy the file name with funtions
lets generate some more erros now
Can I make something like channel.send but with discord account not in bot?
Request?
acutly u can
but will eventualy lead to your discord id to be ban
maybe ip too
Acktuarly ๐ค
u want a owo slef bot right
The question regarding "self bots" has come up here and there, and we'd like to make our stance clear:
Discord's API provides a separate type of user account dedicated to automation, called a bot a...
๐คฃ
jeez

Next up for me: buttons. Does this gist look like it's offering decent advice to anyone else?
https://gist.github.com/lykn/bac99b06d45ff8eed34c2220d86b6bf4
A gist which shows/tells you how to make buttons using discord.py v2(version 2.0.0a) - buttons.md
it's a little outdated
there is one thing that makes my eyes suffer (not actual syntax error)
client=commands.Bot(command_prefix=".")
naming a Bot instance client
eg, the interaction and button parameters in the callbacks should be swapped
aside from that it should be fine though
yeah. horrible.
i know right
Actually some of the examples look incorrect to me
right up there with import pandas as np
xd
If there's something better out there, just point me in the right direction!
(BTW, shout out to #discord-bots message That enabled me to add slash commands very easily)!
yeah the gist seems fine mostly view components itself are simple its more about how u handle the interactions the libraries have made pretty nice wrappers over the components
Thanks all. As long as it's not me taking down some road I'll later learn to regret, that's fine for now.
are you developing this gist or you are looking for something to learn
Ha! I only wrote my first line of discord bot code yesterday!
So, definitely in learn rather than teach mode for now.
in this case there is a whole directory on discord.py github containing examples
even about buttons and other components
you can find it under views directory
diskane ftw

That right there is what I find missing from the docs. Knowing that something is described and where to find it!
yeah they dont mention it anywhere
hmm tru they dont link
but it exists!
disnake has guides on their site
Yep, now I know where to look there's some good stuff in there. Thank you.
๐
No idea if something I've done is well known or not. Happy to write it up if it helps...
I have my bot running in a docker container with a github action to build an image for that and push it to the github package registry. My production box then just has a docker compose file to pull that (along with a .env file for a few variables) and nothing else.
The image also handles my local dev copy - production has the bot installed as a wheel, dev mounts the local source code folder into the container.
oh, and it's multi-platform - production runs on a pi.
are you willing to share the compose file and the gh-action i was trying to do something like this but ended up logging in to vm and pulling the code from github and building docker image on vm directly
@burnt island ^
no need to bump your post when its 1 message above
so wait
until somebody does help you
Sorry, was making coffee. Let me grab a link...
no worries
thanks
u can copy compose file of pokelore i already did that for it except the deployment part u can register a vm for deployment via self hosted runners for github iirc
it uploads to registry? never looked at it
Any errors?
dosent upload to registry for the one i made that would defeat the purpose of having a private repo it builds the image on pushing for test purposes
i dont have a vm so i didn't make the vm deployment part
you can have a private package - in fact, it's the default
you have to jump through an extra hoop to make it public
even on a public repo
that makes sense
ah yeah then i already did the part with docker compose and github action but it did not built image it just pulled the code to vm and built it here
name: Deploy Discord bot
on:
push:
branches: [main]
workflow_dispatch:
env:
REPO_NAME: ${{ github.event.repository.name }}
REPO_OWNER: ${{ github.repository_owner }}
USER: down
jobs:
push:
name: Build & Push
runs-on: ubuntu-latest
environment: Staging
steps:
- name: Tag latest
uses: appleboy/ssh-action@dce9d565de8d876c11d93fa4fe677c0285a66d78
with:
host: ${{ secrets.SSH_HOST }}
port: 22
username: down
key: ${{ secrets.SSH_PRIVATE_KEY }}
passphrase: ${{ secrets.SSH_PASSPHRASE }}
script: |
cd /home/${{ env.USER }}/${{ env.REPO_NAME }}
git pull
docker compose build
run:
name: Run
needs: push
runs-on: ubuntu-latest
environment: Staging
steps:
- name: Build Docker Image
uses: appleboy/ssh-action@dce9d565de8d876c11d93fa4fe677c0285a66d78
with:
host: ${{ secrets.SSH_HOST }}
port: 22
username: down
key: ${{ secrets.SSH_PRIVATE_KEY }}
passphrase: ${{ secrets.SSH_PASSPHRASE }}
script: |
cd /home/${{ env.USER }}/${{ env.REPO_NAME }}
docker compose up -d
ig I'll look into it when i deploy it
thats a long code block
i see
which is not perfect
That gh action is working nicely for me - just need to rename the production override file when you copy it somewhere
I might look at using multiple runners for the two platforms, but, with only two, it's not bad right now anyway.
Hey can i have a tip
like i am storign the sever data to be further used in game
so i make the user type start command and then i will store the server data
so what i want to do is
after teh server data is uploaded in my mongodb database
i want to disable the start command
so far what i have though of is
i am storign the guild id as _id in mongodb
so i have to check if that id do exitss
so that i cant be rund next time
or is there any way
that command can only be rund for once per server
guys can someone pls explain how he was able to get the "client" outside the class scope
Who is he
Ask that person
i cant ;-;
hi how can i bypass this error
discord.errors.LoginFailure: Improper token has been passed.
Comments exist
Give a proper token duh
thats the main script
Cool
like when i load the cog script, am i able to use the client variable in it ?
Me when leaked token
bruh he regenerated it for sure
client = commands.Bot(...)
average shit YouTube tutorials
One advice: Stop watching these tutorials
how can learn without them
well .... i dont understand shit in the api
i mean i get confused a lot of time when i read the docs
That's why there are examples and guides
YouTube tutorials are outdated and usually showing bad coding
examples? where can i find them
yeah they are outdated, but they gives the main idea
oh ok
Error says it all though, the token is invalid
but i put the correct one
;-;
Error says otherwise
hm
(user tokens are not correct)
ohhhh
The question regarding "self bots" has come up here and there, and we'd like to make our stance clear:
Discord's API provides a separate type of user account dedicated to automation, called a bot a...
A great way to get your account banned 
so i cant use my acc?
You technically can, your account just may be terminated and banned from Discord, so don't do it
^
import discord, os
from discord.ext import commands
from colorama import Fore, Style
from functions.json import JSONWrapper
from functions.console import *
config = JSONWrapper("config.json")
prefix = config.get("prefix")
token = config.get("token")
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = prefix, intents = intents)
@bot.event
async def on_ready():
cprint("INFO", f"{bot.user.name} ({bot.user.id})")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.{filename[:-3]}")
bot.run(token)```
When I try !ping said ping is not found
and how i do with a bot? i just put the token bot?
Yes
How do I fix the cog system?
await the load_extension
You read the error that says that load_extension hasn't been awaited
Then you can't use await outside of an async function so you create an async function to load your cogs
hen I puI cant
import discord, os
from discord.ext import commands
from colorama import Fore, Style
from functions.json import JSONWrapper
from functions.console import *
config = JSONWrapper("config.json")
prefix = config.get("prefix")
token = config.get("token")
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix = prefix, intents = intents)
@bot.event
async def on_ready():
cprint("INFO", f"{bot.user.name} ({bot.user.id})")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
await bot.load_extension(f"cogs.{filename[:-3]}")
bot.run(token)```
Here again, reading will help
i can join in a bot acc?
What is join in a bot acc
Put the bot token and run the file
Then invite the bot in the server
i want to join in this acc
how
A bot must be invited in servers
To invite a bot you must have manage servers permissions
oh
ok so i cant do this
but ty
stop using token ids
i use what then
i mean real ids tokens
๐ง
You're late my guy
ig yes
how can i get that
You get your bot token from the screenshot you've put above
oh yea
If you can't invite the bot in the server there is no point, that's it
๐
auto react
Yes, you will get your account banned
ok ty for the information
Hey i need to know the code what customize a discord bot's Bio please ๐
You do that in developer portal
no i want to do it on script better ๐





