#discord-bots
1 messages Β· Page 90 of 1
if you dont understand something ; come back and ask
which ai is this
google vision ai didnt work
It even described all the liens and if it makes an object.
Google optical character recognition
thats what im using
and it return DC
why does it return DC
does discord have any protection against people who bot the bots
they have hcaptcha
which is still easily bypassable
If you mean bots solving captcha's/ reacting then no.
But they do have some tricks up their sleeves.
trying to think how you'd implement something that a bot couldn't bypass on discord
they could just do what coinbase does
get id proof
π
im sure that wouldn't kill your bot
The best way to have a captcha that is harder to be botted by discord accounts is to take it off discord, and use an actual captcha
i wonder why most bots havent done that
nvm
You defined it as data
Well image based captcha's get a long way since google still has that api for google devs only.
Wait
...
They defined it, but you didn't
do u have any files named captcha?
including the bot file
lol i didnt even read this
show the code
Only thing that I can see is the error's description
first off : dont use nextcord
second off : dont kick the user if they fail once
some captchas are so hard to read i literally cant solve them
how many times have u failed a captcha
give them 3 attempts
make a dict
ok
make a json file
def writeJson(userID: str, attempts):
with open('questions.json', 'r+') as file:
fileData = json.load(file)
fileData["captchaAttempts"][userID] = attempts
file.seek(0)
json.dump(fileData, file, indent=4)```
check their attempts by loading the json, similar to this but just dont dump anything
then if they get it wrong, subtract their attempts by 1 and writeJson again
after u subtract the json and it reaches under 0
kick them
example usage: writeJson(str(message.author.id), 3)
pep_number
!pep <pep_number>
Can also use: get_pep, p
Fetches information about a PEP and sends it to the channel.
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Oh thanks
what
It can't open the font file
Couldnt find anything online on how to do something like that
But I randomly saw it here
me too
i spent ages trying to find that example
no
consider using aiofiles instead of open
its ur pc error π
!pypi aiofiles
C drive is really strict on files opened from unknown source
use aiofiles to open then use json.loads to load it
thats why i use usb
that way it won't block
you could open a file with a non async method but for file-reading it's better to use aiofiles
use aiofiles
but u can still easily corrupt the file
"bytesio will do the file" π
thats for buffering its not gonna open and read the file
ikr
does the captcha module directly make the file
or does it return bytes content
lemme see ur code
thanks, u can use pillow to open right?
it's non-async
pillow is blocking too
oh
u need to run it in a thread
discord thread or python thread
discord ofc
your bot will be ratelimited
u will get ratelimited a lot
is this bot public
or for personal use
it may be alright if u limit the number of threads
and then close them for inactivity
discord itself should have a limit of thread per-channel
yea
work on the economy asap
and make it hard
but not too hard where people get bored
and not repetitive
if you add tons of new stuff to the economy then more and more people will come
ded
Why would you need intent for modlogging?
Hello
I have an error says event loop closed and it come out of no where it doesnt let me run my code
more features != better bot
Probably members, messages
focus on making one very good feature
It says something about python software doesnβt respond
Anyone can help me?
nice
Very true, most people want separate bots for separate tasks.
I want some help
Pretty much, If it's a private bot I understand but else, why bother.
show the traceback
right, that was my point
It traces back to my python file
users will also probably just use one feature (the best feature offered by the Bot) so all the other features are just a waste of time and memory
it's not necessarily about that, it's true for any app or thing
imagine if google decided to make their homepage cluttered with stuff like weather and other random features
Show. The. Traceback
Stop describing windows smh.

everything that comes into the terminal, jesus
amen
good point. I'm thinking of switching over to linux π
im switching to templeOS tbh
I got a Linux running rn to see if I can run everything smoothly with what I'm doing on Windows. I've got to say, I am having some hiccups.
Python implementation in holy c? 
Enable intents in the discord dev portal website.
you haven't enabled intents on your bot's developer page but are seeking disabled intents from your code
holy c is the language of the future tbh
I also recommend fully reading the traceback since it also literally contains the url.
I see
oh ok
Why would you want to know that?
thank you now i can make this type of stuff
you can't find who deleted a message
Well actually the audit log could have a pretty good guess on who removed it.
rarely captures it
Audit log only logs deletions, and only if they were deleted by someone other than the message author
edited not delete
message.guild returned None
Was the message sent in a server, or a dm?
i think that happens if someone tries to use it in a dm
only if ur bot can handle it
one way i can think of doing this is have a dict with unix timestamp
and then every 1 hour you loop through every user to see when their last command was and if its smaller than the unix timestamp u saved then send a dm to them
prob a bad idea but its one way
Yes
otter
Yeah you need to have a table with users and last command usage times, store the time when on_command (or on_command_invoke idr) and in the loop just select all users with time less than 3 days ago from current time, send them a message and delete them from table to prevent bot from continuosly sending messages
How to import discord _games
Because I'm getting error
ModuleNotFoundError : No module named 'discord_games'
What is discord_games
How do i register both appcomamnds and prefixed commands
my on_message event don't let that the commands work
When i typing
pip install discord-games
Another error coming is
File "stdin>", line 1 pip install discord-games ^ SyntaxError : invalid syntax
@vocal snow
@app_commands.command(name="set")
async def set(interaction:discord.Interaction):
await interaction.response.send_modal(name())
await interaction.response.send_message("Done")
Not getting the slash helpppp
That's not python code, it's a command for terminal
@vocal snowcan u help me
Are you using discord.py? Check out hybrid commands
Then how will you use prefixed command
How to do that
I need to add the app commands
Gimme a test example without classes with both prefixed cmd1 and slash cmd2
See second pinned message for slash command guide
Why it says botBase.load_extension was never awaited
In discord.py 2.0 load_extension and add_cog are coros, you need to await them
When I await them it then says await outside function
@vocal snow btw how do i add all the guilds
You can only await inside async functions
Wdym
@vocal snow self.tree.copy_global_to(guild=discord.Object(id=12345678900987654))
@vocal snow
class SlashBot(commands.Bot):
def __init__(self) -> None:
super().__init__(command_prefix=">", intents=discord.Intents.default())
async def setup_hook(self) -> None:
#self.tree.copy_global_to(guild=discord.Object(id=12345678900987654))
await self.tree.sync()
#bot = SlashBot()
client = SlashBot() ```
Got no response to my prefixed cmd as well as slash cmd btw hybrid cmds are working with only slash
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
What is format_emb
how would the json file for that code look like. Will it be a dict or a array?
i think looking at this it's pretty much understandable
what are some must have channels for a bot server
that it would be a dict
Makes sense
app_commands.command decorator only creates a Slash command object
You need to add it to the bot
How
Or just use @bot.tree.command decorator
if format_emb is a class which i think it is, this might me shadowing it
idk if that affects anything tho
No it's supposed to be a string
@client.tree.command(name="set")
async def set(interaction:discord.Interaction):
await interaction.response.send_modal(name())
await interaction.response.send_message("Done") ```@vocal snow still cmd not registered
oh sorry, .format is a string method
i forgot bruh :dumb:
wait now u have a f string and using format on it wt
See you're doing {ctx.author.id} inside the string
But you aren't providing ctx to .format
You should change the ctx.author.id to author_id
Not necessary
oh ok
You can pass as positionals or as kwargs
@vocal snow hey why is my cmd not added to bot
Anyways, idk why an fstring isn't being used
I don't know, send code please
@client.tree.command(name="set")
async def set(interaction:discord.Interaction):
await interaction.response.send_modal(name())
await interaction.response.send_message("Done")
@client.event
async def on_ready():
await client.add_cog(anti(client))
#tree = app_commands.CommandTree(client)
await client.tree.sync()
This was above the previous one
cogs in on_ready π€’
that way to load cogs is so ass btw
replit is being dumb
it used to work yasterday fine
and today i get hit with this error:
File "main.py", line 63, in <module>
client.run(os.environ['TOKEN'])
File "/home/runner/Yoink-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())```
firstly, you shouldn't be hosting on replit. Secondly, is that the whole error?
show the whole traceback.
File "main.py", line 63, in <module>
client.run(os.environ['TOKEN'])
File "/home/runner/Yoink-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run
asyncio.run(runner())
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/home/runner/Yoink-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "/home/runner/Yoink-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start
await self.login(token)
File "/home/runner/Yoink-Bot/venv/lib/python3.8/site-packages/discord/client.py", line 580, in login
data = await self.http.static_login(token)
File "/home/runner/Yoink-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/home/runner/Yoink-Bot/venv/lib/python3.8/site-packages/discord/http.py", line 680, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): ```
what page then?
that is FREE
either you're spamming something, or blame replit
im blaming replit
as of now none
cos its the same code as yasterday
only way rn cycle heroku and railway accs
bruh
if u have a cc just use aws
cc?
credit card
just go check discord bot hosting
.name
what is this error in json
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'are'```
'are'?
Code?
You're attempting to check for a key that doesn't exist
It means that there isn't a key with the name "are"
@bot.command(aliases=["8ball", "8balls", "eb"])
async def eball(ctx, question):
random_reply = random.choice(r8ball)
with open("eballdata.json", 'r') as f:
questions = json.load(f)
if str(question) in questions:
await ctx.send(questions[str(question)][random_reply])
else:
await ctx.send(random_reply)
questions[str(question)][random_reply]
with open("eballdata.json", 'w') as f:
json.dump(questions, f)```
see there is no key named are
can i trigger a command with a button or other command ?
Looks good to me
https://discord.com/oauth2/authorize?response_type=code&client_id=995673825511485470&scope=identify+guilds.join&state=15773059ghq9183habn&redirect_uri=136.243.69.245/discordauth
anyone got i idea why it isnt working?
in the dev page?
on the page of your app
go to your current application > bot page
scroll down a bit and enable message intents
but really I'm just trolling
don't listen to me
why are you using str.format though and that too is wrong, why dont you use f-strings?
stop reposting
what do i need to install for the modules that arent installed its confusing me
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
ty
no, just remove that and put an f before the emb_format string, which makes it an f-string (see !f-string in #bot-commands for more info), and then you can directly reference that variable in the value like value=emb_format
!e```py
name = "Ashley"
string = f"My name is {name}"
print(string)
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
My name is Ashley
can someone help?
smh no
winners = 0
emb_format = f"winners {winners}"
embed.add_field(..., value=emb_format)
What does that translate to?
how can I make my 8ball responces parmanent
probably a broken identifier
invalid url format#
parmanent?
like if u ask the same question over and over again then it will provide u the same answer
like if u ask the same question over and over again then it will provide u the same answer
sorry of double
make a cache maybe?
a dictionary that stores the last question and the response provided, then use a library like difflib or fuzzywuzzy to check the string similarity and send back the same response or a new one
I know that it is used but idk how it is used
where can I learn this
oh god, emb_format was just an example, remove that winners and all
just simple havre the format_emb and then pass it to the value. no parameters at all
format_emb = ...
embed.add_field(..., value=format_emb)
await send(embed=embed)
easy as that
right
define members and winner_count too lmao
before you use them in format_emb
members = ... winner_count = ...
Is there like an only_for_server_ids function?
could you elaborate? your use case and what exactly does that mean
huh
see the pins in #965291480992321536
like this command can only be used if the server the command is being executed is one of the server id's
like i have 3 servers and i want a command to restrict to 1 server
Question:
How do i put 2 buttons in 1 button callback ?
Code:
async def button(ctx):
buttons = [
Button(label="Title", style=discord.ButtonStyle.primary),
Button(label="Title", style=discord.ButtonStyle.primary)
]
async def button_callback(interaction: discord.Interaction):
first_embed = discord.Embed(title="Title", description="Description")
await interaction.response.edit_message(content="Editing embed!")
buttons.callback = button_callback
view = View(timeout=None)
view.add_item(buttons)
await ctx.send(content=None, view=view)```
**Error:**
```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'callback'```
if ctx.guild.id == db or just a dict?
!d discord.ext.commands.guild_only
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
If used on hybrid commands, this will be equivalent to the [`discord.app_commands.guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only "discord.app_commands.guild_only") decorator. In an unsupported context, such as a subcommand, this will still fallback to applying the check.
create a custom check, or check ctx.guild.id inside the command
pls help π
yes you can ```py
buttons[0].callback = button_callback
buttons[1].callback = button_callback
ok
how do i put this in my code ?
like what do i do with the list ? i keep it a list or do i do smth else ?
just the same ig?
?
you don't need a list at all in the first place
async def button(ctx):
buttons = [
Button(label="Title", style=discord.ButtonStyle.primary),
Button(label="Desc", style=discord.ButtonStyle.primary)
]
async def button_callback(interaction: discord.Interaction):
first_embed = discord.Embed(title="Title", description="Description")
await interaction.response.edit_message(content="Editing embed!")
buttons[0].callback = button_callback
buttons[1].callback = button_callback
view = View(timeout=None)
view.add_item(buttons)
await ctx.send(content=None, view=view)```
what do i do ?
yes this will work except you'll get an error at the view.add_item.line
for button in buttons: view.add_item(button)
``` replace it with this and it should work
and i keep the list on top ?
yea
@bot.command(aliases=['bal'])
async def balance(ctx, user:discord.Member = None):
if user is None:
user = ctx.author
cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones = await get_bal(user)
balem = discord.Embed(title=f"**{user}'s balance**", color=discord.Color.purple())
nl = '\n'
balem.description = f"**Cash:** {cash} {nl} **Crystals:** {crystals} {nl} **Event Pearls:** {event_pearls} {nl} **Weapon Shards:** {weapon_shards} {nl} **Fusion Earrings:** {fusion_earring} {nl} **Merging Stones:** {merging_stones} {nl} **Enhancing Stones:** {enhancing_stones}"
balem.set_footer(text='Alaias - bal')
await ctx.send(embed=balem)
``` I can look my bal but cannot look at other's bal, why is that?
k ill see if it works
the indentation, rest of the code after user = ctx.author has to be un-indented by one block
it does thanku very much π but 1 more question how do i now add another value to the buttons ? ```
i c
can you elaborate wdym by "add another value"
yes like the 2 buttons do the same thing now i want them to do smth else
well then create 2 different callbacks and assign the callback accordingly
can i not do smth like button.values or smth
there's a much better way to do this if you know how classes work
i dont
miss ashley will explain you the rest i gtg
well then it would look like this ```py
async def callback1( ...): ...
async def callback2(...): ...
buttons[0].callback = callback1
buttons[1].callback = callback2
callback1 and callback2 being functions like your button_callback function earlier
or ssmth
How do I do the background for created_at?
like the select interaction
thats another thing, totally not related
create a spoiler.
but does it work ?
thats an unix timestamp
an
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
no
why does it work for select but not for button ?
because a button is a button and a select is a select
ok well what if i want to make it in 1 callback ?
is there like a way that looks like it ?
ok so this is what i get
AttributeError: 'list' object has no attribute 'values'
the same list error again
discord.utils.format_dt()
what do I need to type if I want to get the years? (Created At)
format_dt() is not used for extracting years out of a datetime
So how I get the years?
!d datetime.datetime perhaps the attributes of the class may be of interest
class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)```
The *year*, *month* and *day* arguments are required. *tzinfo* may be `None`, or an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass. The remaining arguments must be integers in the following ranges...
To get this one
What's wrong with ctx.guild?
There is no ctx, I'm guessing whatever library they're using doesn't provide it
smth like this?
@bot.command(aliases=['bal'])
async def balance(ctx, user: discord.Member=None):
if user is None:
user = ctx.author
cash, crystals, event_pearls, weapon_shards, fusion_earring, merging_stones, enhancing_stones = await get_bal(user)
nl ='\n'
balem = discord.Embed(title=f"**{user}'s balance**", color=discord.Color.purple())
balem.description = f"**Cash:** {cash} {nl} **Crystals:** {crystals} {nl} **Event Pearls:** {event_pearls} {nl} **Weapon Shards:** {weapon_shards} {nl} **Fusion Earrings:** {fusion_earring} {nl} **Merging Stones:** {merging_stones} {nl} **Enhancing Stones:** {enhancing_stones}"
balem.set_footer(text='Alaias - bal')
await ctx.send(embed=balem)
<t:1569079137:R> there you go
Yes yes how?
unindent smh
Use <t:TIMESTAMP:FLAG> to send it
Available flags:
t: Short time (e.g 9:41 PM)
T: Long Time (e.g. 9:41:30 PM)
d: Short Date (e.g. 30/06/2021)
D: Long Date (e.g. 30 June 2021)
f (default): Short Date/Time (e.g. 30 June 2021 9:41 PM)
F: Long Date/Time (e.g. Wednesday, June, 30, 2021 9:41 PM)
R: Relative Time (e.g. 2 months ago, in an hour)
How do I put it on my code? for the created_at
why this error-
Oh just use the utils function format_dt()
discord.utils.format_dt()
and what should be inside the brackets to show me the years..
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
i think you can do smth like {ctx.author.mention} or smth instead of <@...>
also
put an f infront of it
infront of " "
np
Hello everyone! I want to add a command thats only usable in a ticket channel. The ticket channel always has a new number at the end. So how could i do this?
a close command?
no a add command so you can add someone from the server to the ticket
@client.command()
async def add_user(ctx, channel : discord.TextChannel = None, user : discord.Member = None):
if channel == None:
await ctx.send("Enter a User to add")
else:
channel = channel or ctx.channel
overwrite = channel.overwrites_for(user)
overwrite.send_messages = True
overwrite.read_messages = True
await channel.set_permissions(user, overwrite=overwrite)
await ctx.send(f'Added {user.mention} to the Channel')
gives them perms to see and talk in the channel
but isnt that command available in every channel then?
yeah but u can change it to whatever you want
but how? I only want it to be used in tickets and the names are like ticket-#1 and i dont want someone use it in other channels that are only for staff
if ctx.channel.name.startswith("ticket"):
Are you just spoon feeding?
no idea what that means
if i ping the user before sending the embed will it cache the user?
spoon feeding = sending solution instead of explaining or teaching
Is it possible to get the message id of a message when a button attached to the message gets pressed?
Oh my bad
whats the json response?
youβd get the message associated with that button's View.
hey how can i make a double use command for instance if i run it once it will say hi but if i run it again it will say goodbye? i also want to make a channel private via my discord bot
i need help making a dropdown menu
i have a button option and after someone clicks the button i need the bot to send a dropdown menu option
Hi everyone, is it possible to use selenium with discord api ?
You can use anything with anything. The real question is how well will it work. The answer to that is: not very well. At least, without multiple processes or threading
selenium was meant to interact with browsers
selenium is sync ?
I know it but if selenium is not async it will not really work as well
Yes, that's what I'm saying
is there any way other ?
Like for requests, instead of requests : there is aiohttp for async
the same thing for selenium
or the same to scrape data of dynamic website
idk how to make it so it sends an embed after a button is pressed can someone help?
if data[str(guild.id)]['users'][str(int.user.id)]['open_tickets'] <= data[str(guild.id)]['max_tickets']:```
it continues to create a ticket even though there is more tickets than aloud
max ticekts is 2 and i can create well over that
int is the interaction
how about len()
everything is synced
so i do len(data) <= len(data)?
idk how to make it so it sends an embed after a button is pressed can someone help?
a button or a emoji
did you do a callback for t he button?
so when someone presses button a
i need it to send an embed
so then it does await ctx.channel.send(embed = embed)
did you do a clalback for it?
im new to python idek what that means ;-;
a callback function is something that adds onto the button after it is pressed
is yours a class or just a simple inside the command
import discord
client = discord.Client(intents=discord.Intents.default())
class YourBetterClassName(discord.ui.View):
def init(self):
super().init()
self.value = None
@discord.ui.button(label='Hi', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('hi', ephemeral=True)
self.value = True
self.stop()
@discord.ui.button(label='Help or Question', style=discord.ButtonStyle.grey)
async def b(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Please Ping a Mod/Owner', ephemeral=True)
self.value = False
self.stop()
@client.event
async def on_guild_channel_create(channel):
await channel.send(view=YourBetterClassName())
this is my code
should i do
instead of send message do send embed after interaction
import discord
client = discord.Client(intents=discord.Intents.default())
class YourBetterClassName(discord.ui.View):
def init(self):
super().init()
self.value = None
@discord.ui.button(label='Hi', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('hi', ephemeral=True)
self.value = True
self.stop()
@discord.ui.button(label='Help or Question', style=discord.ButtonStyle.grey)
async def b(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Please Ping a Mod/Owner', ephemeral=True)
self.value = False
self.stop()
@client.event
async def on_guild_channel_create(channel):
await channel.send(view=YourBetterClassName())```
ok so you have a class
yes
on the await interaction.response.send_message(embed = embed, ephemeral = True)
should i just remove that
https://cog-creators.github.io/discord-embed-sandbox/
because i dont want it to send a message i want it to send a embed
here is a gerat embed creator but doesnt have some features
only on the first button
yeah thats what i used
do
interaction.response.send_message(embed = embed, ephemeral = True)```
its embed = embed
so
@discord.ui.button(label='Hi', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message(embed = embed, ephemeral = True)
then put the embed code
@discord.ui.button(label='Hi', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
#Embed Coding Here
await interaction.response.send_message(embed = embed, ephemeral = True)```
then it should send your embed everytime your button is pressed
ok it works
but now its not showing the 2nd button option
hmmm
Indent error
Are you new to python?
Indents are hard to explain how they work but once u know how they work, it's easy
!indents
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
yes
I'd say read the text above and if u don't get it google about indents
i tried all different indentations
Send screen of ur code
@discord.ui.button(label='Hi', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
embed=discord.Embed(title="Hi", description="Hiii.", color=0xc32828)
embed.add_field(name="123 π", value="2", inline=False)
embed.add_field(name="456 π", value="1", inline=False)
await interaction.response.send_message(embed = embed, ephemeral = True)
this is my code
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
If u send ur code without using this way we can't see indents
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
embed=discord.Embed(title="Hi", description="Hiii.", color=0xc32828)
embed.add_field(name="123 π", value="2", inline=False)
embed.add_field(name="456 π", value="1", inline=False)
await interaction.response.send_message(embed = embed, ephemeral = True)```
@discord.ui.button(label='Hi', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
embed=discord.Embed(title="Hi", description="Hiii.", color=0xc32828)
embed.add_field(name="123 π", value="2", inline=False)
embed.add_field(name="456 π", value="1", inline=False)
await interaction.response.send_message(embed = embed, ephemeral = True)```
Also, could u maybe screen it? I'm on phone
screen share?
nah screenshot
await interaction.response.send_message(embed = embed, ephemeral = True)
is not inside of a function
yet it's indented like it is
so python is confused on what you mean
it's not about trying different indentations, it's not a game. You need to know how to define functions and which lines of code are part of it
That beings said, how do you define lines of code to be within a function?
following this everything shouldnβt all be inline
i got it to work
but this happend
this is so frustrating
@discord.ui.button(label='Hi', style=discord.ButtonStyle.green)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
embed=discord.Embed(title="Hi", description="Hiii.", color=0xc32828)
embed.add_field(name="123 :paperclip:", value="2", inline=False)
embed.add_field(name="456 :paperclip:", value="1", inline=False)
await interaction.response.send_message(embed = embed, ephemeral = True)
self.stop()```
@slate swan this is right?
Can I see the view initializer?
what are you trying to create
this?
are you leavingg code out?
import discord
client = discord.Client(intents=discord.Intents.default())
class YourBetterClassName(discord.ui.View):
def init(self):
super().init()
self.value = None
@discord.ui.button(label='Hi', style=discord.ButtonStyle.grey)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
embed=discord.Embed(title="Hi", description="Hiii.", color=0xc32828)
embed.add_field(name="123 :paperclip:", value="2", inline=False)
embed.add_field(name="456 :paperclip:", value="1", inline=False)
await interaction.response.send_message(embed = embed, ephemeral = True)
self.stop()
@discord.ui.button(label='Help or Question', style=discord.ButtonStyle.grey)
async def b(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Please Ping a Mod/Owner', ephemeral=True)
self.value = False
self.stop()
@client.event
async def on_guild_channel_create(channel):
await channel.send(view=YourBetterClassName())```
this is my whole code
a automatic bot for my server
when someone makes ticket
why not when you create the ticket it auto matically sends the embed?
because it needs button options
A view only includes message components. You need to send some form of content, whether it be message content or an embed.
i just need it to send a embed after button "hi" is pressed
Like I said, you need to include some kind of message content. For example,
await channel.send("these are some buttons:", view=YourBetterClassName())
ok
I would also take the suggestion of YourBetterClassName and use a better class name
so send that before embed
before what embed?
idek where to put this
Well
U cant just send a naked button. It has to be stickied to a message
See the buttons below?
yes
They're stickied to the message
ok
U need to send a message and add buttons to that message
so u want me to put something
like await interaction.response.send_message('Please Ping a Mod/Owner', ephemeral=True)
before the embed
u can add buttons on an embed too
U just need some kind of message to add the buttons to
It does
still doesnt work
2022-09-21 22:51:06 ERROR discord.client Ignoring exception in on_guild_channel_create
@discord.ui.button(label='Hi', style=discord.ButtonStyle.grey)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Please Ping a Mod/Owner', ephemeral=True)
embed=discord.Embed(title="Hi", description="Hiii.", color=0xc32828)
embed.add_field(name="123 :paperclip:", value="2", inline=False)
embed.add_field(name="456 :paperclip:", value="1", inline=False)
await interaction.response.send_message(embed = embed, ephemeral = True)
self.stop()```
ugh
still empty message
???
Adding buttons to a message require the view parameter
await ctx.channel.send_message("Hello", view = Yourview())
undefined name ctx
where do i put this
Send code
I see a lot of mistakes in ur code above
Please look up the docs and their examples
import discord
client = discord.Client(intents=discord.Intents.default())
class YourBetterClassName(discord.ui.View):
def init(self):
super().init()
self.value = None
@discord.ui.button(label='Hi', style=discord.ButtonStyle.grey)
async def a(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Hi', ephemeral=True)
embed=discord.Embed(title="Hi", description="Hiii.", color=0xc32828)
embed.add_field(name="123 :paperclip:", value="2", inline=False)
embed.add_field(name="456 :paperclip:", value="1", inline=False)
await interaction.response.send_message(embed = embed, ephemeral = True)
self.value = True
self.stop()
@discord.ui.button(label='Help or Question', style=discord.ButtonStyle.grey)
async def b(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_message('Please Ping a Mod/Owner', ephemeral=True)
self.value = False
self.stop()
@client.event
async def on_guild_channel_create(channel):
await channel.send(view=YourBetterClassName())```
Decorators
A decorator is a function that modifies another function.
Consider the following example of a timer decorator:
>>> import time
>>> def timer(f):
... def inner(*args, **kwargs):
... start = time.time()
... result = f(*args, **kwargs)
... print('Time elapsed:', time.time() - start)
... return result
... return inner
...
>>> @timer
... def slow(delay=1):
... time.sleep(delay)
... return 'Finished!'
...
>>> print(slow())
Time elapsed: 1.0011568069458008
Finished!
>>> print(slow(3))
Time elapsed: 3.000307321548462
Finished!
More information:
β’ Corey Schafer's video on decorators
β’ Real python article
im watching a vid on how to make a discord bot and i came across this line
should that data be reviled?
dont understand any of this :))))
its this vid:
Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
π¨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables
Along the way, you will learn to use Repl.it's built-in database and cr...
1:01:17
don't do that
the discord bot videos are garbage
they're probably using replit or heroku for hosting
i already did that
but can somone do someting with that info
replit is dogshit however it is free sooo
got it to work
:DDD
how do i make it so its not only i can see it and other people can see it
U can't use interaction.response.send_message twise , use interaction.followup.send
yeah i realised
dyk how to make it so when the bot sends that its not only you can see this?
ostias
async for user in channel.guild.audit_logs(limit=1):
await ban(user, reason=None, delete_message_days=1)
oh
I'm at an event xd
I didn't do any class
!d discord.Member.ban
await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
why would you be able to call ban on the bot instance
im not understand XD
I'm guessing bot.ban() was an older version? Like bot.say() or similar?
I should probably go to sleep, I didn't even realized
idk im just tired and got confused π€¦
aaaaaa what
m
I cant help you rn I need some sleep and cant help anyone like this...
Okok
xdd
.ban needs to be called on a member instance
user.ban
instead of bot.ban
i think its better to use member instead of user
because a member refers to an user inside a guild
right?
oko
'AuditLogEntry' object has no attribute 'ban'
what value should i give it?
@sick birchSorry for the mention, how can I solve this problem?
!d discord.User.ban
No documentation found for the requested symbol.
await ban(user, *, reason=None, delete_message_days=..., delete_message_seconds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
i dont understand
What do you not understand?
when i use await ban it gives me an error, then if I try to ban a user it gives me the error 'AuditLogEntry' object has no attribute 'ban'
Sorry if I say something wrong, I speak Spanish
!d discord.on_message
yes because user is an AuditLogEntry
even though you passed in limit=1 it's an async iterator
it really only has one element but it's still an iterator
I understand, and how do I stop being an iterator
async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guildβs audit logs.
You must have [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") to do this.
Examples
Getting the first 100 entries:
```py
async for entry in guild.audit_logs(limit=100):
print(f'{entry.user} did {entry.action} to {entry.target}')
```...
refer to the documentation here
Can i add nitro emojis to my embed like
?
Is there another way to ban a user when creating a channel?
m
m?
\πΆβπ«οΈ
@slate swan
\
I don't know
if len(data[str(guild.id)]['users'][str(int.user.id)]['open_tickets']) >= len(data[str(guild.id)]['max_tickets']):```
\π
XD
doesnt work even when i set my tickets to 0 could i get help?
why isnt it sending emoji id
I don't know
what are you attempting to do?
add a nitro emoji to my embed
like 
where are you putting the emoji
because some places will not work and will just show :emoji:
in the text
are you using the emojiname:emojiid
no i did \ emoji
yes theat send the emoji name and id
<ablobhammer:586031065219596302>
<π :emojiid>
does work??
idk how to get emoji id
just do back slash your emoji
:w:
it sends that
nvm
?
it worked
977412187473719296 is the id
does anyone know how to make it so everyone can read this?
embed
instead only you can see this
remove ephemeral
above
ok
if len(data[str(guild.id)]['users'][str(int.user.id)]['open_tickets']) >= len(data[str(guild.id)]['max_tickets']):```
it wont go past this
any reason why??
does anyone have an idea on how I can make this?
the 3 minutes ago part?
what parts do u not know
tags, page system, minute ago
well im not sure about tags and page system but i can help you the the minute ago
<t:unixtimestamphere:R>
!d discord.utils.format_dt if you have a datetime.datetime object
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
@slate swan did you fix your problem?
no xD
I'm looking for someone to help me code a Restore bot, so if my server gets deleted i can restore my members
How do you plan on "restoring" members?
Access token or sum
How Letoa or restorecode did it
Using Oauth? you'll need to setup a website for that
can someone help? its saying this is invalid syntax
- Reset your token
- why are you creating 2 instances of the same thing and naming them completely different things?
huh?
I would change your message content sir
i dont understand number 2
i reseted token dw
do if message.content.lower
So if they do !BlAckJack
It will work
the
bot = commands.Bot ('!')
has syntax error
thats my problem
client and bot will be the same thing
just stay with one
no, remove the whole bot = commands.Bot(...) thing, just use client as your bot object
also, just as best practice, you should name it bot instead of client
how would i have a prefix then?
you're already setting a prefix in your bot constructor
you're not closing your parenthesis
that's basic python, you're not defining prefix, and I'm guessing you're not defining intents either
read the error lol
u dont see where i put intents?
i put intents under bot = commands
im VERY new to python
you need to put the intents inside the bot constructor
!resources I don't think discord bots are a good idea then. Knowing intermediate python will only help you
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
commands.Bot takes multiple required arguments
should i add client = commands.Bot(command_prefix = prefix, intents = intents
Yes.
I think learning Python first is really a necessity here
No, it's not
Because you'll keep running into issues like this, that are all 2 minute issues. That adds up
It's only going to discourage you, since you're fighting with the language instead of using it as a tool
I just need help on where to end the parenthesis man.
The problem here is that
- You're missing a closing parenthesis
- You still have 2 instances of the same thing (
commands.Bot) - You're defining
intentsafter referencing it
That's only a short term solution
I really don't like turning people away from coding what they enjoy, but at certain points they'll end up doing that to themselves by not knowing intermediate python before discord.py, which is not a beginner's library
is there a way to get audit log entries for enabling community?
im stupid asf i forgot how to use fore for like 15 mins
π
happens to all of us
Guys how i can get image from message in dpy?
!d discord.Message.attachments
A list of attachments given to a message. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
Anybody got any resolution ? This is the error im recieving await message.reply('What do you need to acquire from the One and Only Suspect. @glass ledge', mention_author=True) ^ IndentationError: unindent does not match any outer indentation level
the indent of the print statement and await message.reply need to be the same
what you did is
if 'suspect' in message.content:
print(f"""Message recieved !""")
await message.reply('What do you need to acquire from the...')
it should be
if 'suspect' in message.content:
print(f"""Message recieved !""")
await message.reply('What do you need to acquire from the...')
Thank you !
np
I got empty list but there is image in the message
you didn't enable the message_content intent
My all intents are enabled
even in the dev portal?
Ye
how to make a cooldown command for a app_command?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!", self_bot=False)
@bot.event
async def on_ready():
print("f Loaded.")
@bot.command()
async def hi(ctx):
embed = discord.Embed(title="r", color=discord.Color.from_rgb(0, 64, 255))
embed.add_field(name="hi", value="hi", inline=False)
await ctx.send(embed=embed)
bot.run("my token",bot=True)
my discord bot doesnt even seem to be working its like 1200 lines, no errors not even this does anything only the bot goes online i cant do any commands though
and yes i have my token in the real code
Damn when was 2.0 released for dpy
few weeks ago
You need message content intents
is it possible to have a discord bot block a user so they cant send them dms?
didnt need that before?
It's it's a new thing
Didn't check for weeks lol
2 hours of debugging just for that thanks though
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(..., intents=intents)
yeah ik
When will the other versions be out
errors
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents, self_bot=False)
@bot.event
async def on_ready():
print("f Loaded.")
@bot.command()
async def hi(ctx):
embed = discord.Embed(title="Elusive - API", color=discord.Color.from_rgb(0, 64, 255))
embed.add_field(name="hi", value="hi", inline=False)
embed.set_image(url="https://cdn.discordapp.com/attachments/971538759516581888/971585692016709663/ezgif.com-gif-maker_1.gif")
await ctx.send(embed=embed)
bot.run("MTAy",bot=True)
is it possible to have a discord bot block a user so they cant send them dms?
What's the error
just traceback call thing on line 4 intents.message_content = True
Traceback (most recent call last): File "C:\Users\User\Desktop\api\a.py", line 4, in <module> intents.message_content = True
import discord
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents, self_bot=False)
@bot.event
async def on_ready():
print("f Loaded.")
@bot.command()
async def hi():
embed = discord.Embed(title="Elusive - API", color=discord.Color.from_rgb(0, 64, 255))
embed.add_field(name="hi", value="hi", inline=False)
embed.set_image(url="https://cdn.discordapp.com/attachments/971538759516581888/971585692016709663/ezgif.com-gif-maker_1.gif")
await ctx.send(embed=embed)``` removed the message content thing but still bot only goes online doesnt respond
self_bot kwarg doesn't exist and you need to enable message content intents
Can you put Snake Game on the next line
channel wasnt found
u did an overwrite on channel
wait, lemme take a look first
I might havent looked good enough
can you print channel for me
why even in the name of god is get_channel inside a try/except block
They want to make debugging their program harder ig
there u got the issue
pass in the correct channel id...
@slate swan do you even try solving problems yourself? Most of these functions is basically done by this community xD
Guys do we need to select application.commands scope to make slash commands work?
Pls anyone tell fast
yes
first make the "soon" stuff. that's gonna take your time lol
Guys how can I get member avater image instead of url ?
I want to paste the user avater on image using pil
Pls help anyone
!d discord.Asset.read
await read()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves the content of this asset as a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") object.
@commands.Cog.listener("on_member_join")
async def join(self,member):
img = Image.open("welcome.jpeg")
avatar = Image.open(member.avatar)
img.paste(avatar)
img.save("avatar2.jpeg")
Guys why i getting this error
You didn't read the avatar data
How to do that?
await member.avatar.read()
Oh k thanks
And if you want to open the image from bytes with PIL, you have to pass it as io.BytesIO or any bytes-like object
import io
...
avatar_data = await member.avatar.read()
avatar = Image.open(io.BytesIO(avatar_data))
do you think that I can made a simple bot in one day
honestly it depends how complex the bot is and also the skill level of the person coding it
It will just return one string
ohk, then just around 10mins (assuming have an avg. laptop which could take a min or 2 to load... and you know how to code related to discord.py)
how do I add this(I am unable to remember the term)
if there are a few questions, let call them tasks and there are 30 of them for each(planet, read the full thing, then u might be able to understand what I mean)
and there are the normal 8 planets so how do I make it so that the tasks(basically a few questions related to the planet and on answering the correct answer u get a specific amount of money) of a planet do not mix up with other planet and the person can select by doing the following cmd - (server prefix) planet (name of the planet/smth similar(provided by the bot) to select a particular)
Example(server prefix - ! ):
! planet
(the bot sends an embed stating:
1 - Mercury, 2 - Venus, 3 - Earth, 4 - Mars, 5 - Jupiter, 6 - Saturn, 7 - Uranus, and 8 - Neptune)
and on doing:
! planet 4
the bot sends the following embed:
You are now one planet Mars(4)
and finally on doing:
! task
the bot sends and embed(example):
Which is the biggest moon for planet Mars:
1οΈβ£ - Phobos
2οΈβ£ - Titan
3οΈβ£ - Deimos
the bot reacts with 1οΈβ£ , 2οΈβ£ , 3οΈβ£
and if the user with the correct a specific amount gets added to their wallet...
PS - Sorry for making it so lengthy...
super vague question, you might as well just be asking how to make a bot
Ok how do i do that?
ye, sry about that, actually I'm still a beginner...
just attempt to make it and then post specifically where you get stuck
the main question is how do I add smth(for the case that I sent above planet) specific questions and how can I make people select a specific planet, it would be fine if u can give me a rough idea, or smth similar on the docs
you'd use the numbers or names of planets in button labels while sending an actionrow in the components arg when you send a message.
ok, i c
then you use the custom ids that you pass in the buttons to see which they press
k
then do I do an if statement to check and send the tasks/questions according or something else?
!d discord.Guild.leave
await leave()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Leaves the guild.
Note
You cannot leave the guild that you own, you must delete it instead via [`delete()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.delete "discord.Guild.delete").
raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 0): <!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en-US"> <![endif]-->
<!--[if IE 7]> <html class="no-js ie7 oldie" lang="en-US"> <![endif]-->
<!--[if IE 8]> <html class="no-js ie8 oldie" lang="en-US"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en-US"> <!--<![endif]-->
<head>
<title>Access denied | discord.com used Cloudflare to restrict access</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta name="robots" content="noindex, nofollow" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" id="cf_styles-css" href="/cdn-cgi/styles/main.css" />```
error on replit
discord bot with webscraper
It looks like you have been rate limited
i put the whole html error into a html reader and got this:
wtf does that even mean
You accessed discord.com too frequently
So this instance of replit is banned from it
ratelimited cuz replit
how do i fix that
Stop your code from accessing discord.com so frequently
its a discord bot
how do i do that
What library are you using
Those listed on the Discord Developer Portal should not be rate limited
import discord
from discord.ext import commands
That tells me nothing about the library you are using
so discord.py ig
I think pycord ?
If you are on replit, you should be able to see what libraries you have installed
how
It's in the packages tab in the editor
Well, the editor is a different view
It's one of the icons on the left side of the window, also where the settings for replit are
replit
3.2.4
5 dependencies
typing_extensions
Flask
Werkzeug
aiohttp
requests
Flask
2.2.2
5 dependencies
Werkzeug
Jinja2
itsdangerous
click
importlib-metadata
discord
2.0.0
1 dependencies
discord.py
bs4
0.0.1
requests
2.28.1
4 dependencies
charset-normalizer
idna
urllib3
certifi
that helps?
Why do you have four different dependencies sections
idk
Also I see you are using requests which isn't asynchronous and therefore is unfit for this kind of a project
discord.py comes with aiohttp which is asynchronous
ill check that out
Hi guys !
I have a serious concern since I just hit the end of the progression curve regarding basic python and discord.py and I now came back to my first bot project that I made (still working and used by 10k+ people thanks to all of u guys that helped me).
I'm getting into some advanced and professional practice such as cleaning my code and make it so it's pep8 friendly. Also reshaping the code to add OOP to it (so it's quite a big redesign).
All of these are going well but where my struggle is with learning unit testing...
And here's my question:
# Returns True if user_id exists, False otherwise
async def check_id(bot, user_id):
try:
await bot.fetch_user(user_id)
return True
except discord.NotFound:
return False
# sayhi command will say hi to the requested id. Syntax: sayhi <discord_user_id>
@bot.command(name='sayhi')
async def sayhi(ctx):
target = ctx.message.content.split(' ')[1]
if await check_id(bot, target):
ctx.send(f'{ctx.author}, you just requested me to say hi to {target} !')
else:
ctx.send(f'{ctx.author}, you requested a wrong ID.')
So since here I'm using discord.py library, with its classes, how am I supposed to unit test these using the unittest library?
but it works fine with it?
should i create different db for each server named with server id and in db make tables ?
or any other approch ?
Whenever an HTTP/S request is made using requests, the bot's code waits for the request to finish and is effectively dead for all Discord is concerned (so the connection may be closed/lost)
a row per server id is preferred
for a single server i have to store economy system + modlogs etc
it will be effactive ?
you can't really do that without having a running instance of "bot" but i think there was a library for discord.py testing
ok ill use the other library
what was the name of it?
create a different table for each functionality then
I think it's aiohttp, and the import line is import aiohttp
why note different db for each ? just asking
alright so the two options are rather using unittest while the bot is running, or use dpy testing lib?
the async version of pytest should just be fine
https://pypi.org/project/pytest-asyncio/
@patent wagon, your replit instance might have been rate limited without your fault because of other people with whom you share the replit instance which have been rate limited (or a combination of both since you are all accessing discord.com in parallel)
is there any way of storing discord channel msg history with bot? like in txt file or any other format
thats your preference then, are you using sqlite?
use a db
i uninstalled discord
now i only have discord.py
Flask
2.2.2
5 dependencies
Werkzeug
Jinja2
itsdangerous
click
importlib-metadata
discord
2.0.0
1 dependencies
discord.py
bs4
0.0.1
wait I don't think I'm using pypi interpreter tho, I think i'm using cpython lemme check this (interpreters are still a bit confusing to me)
says this but it also said i uninstalled discord
Why is it still listed then
Well whatever
By the way are you accessing discord.com using requests or aiohttp explicitly
That matters too
requests
pypi is not an interpreter, its the site you pip install stuff from lol
i think you're confusing it with pypy
ill swich to aiohttp
If you are explicitly accessing discord.com, it might just be that you accessed it too much
im not
stop using replit to avoid that error
im acessing another page
very helpfull t
In discord.com?
wdym
well thats the best help.
A page in discord.com?
im seding a command in discord and it acess another page
you're using a website thats known for causing that issue, not using it is the only solution
what do you mean by a page in discord.com
Any endpoint under discord.com
it access minecrafrservers.org
Well then it's unrelated
It might just be this
In which case this is the best solution
fuck
Ohhhh right Indeed !
any other free ways to host it for free?
thank you again sarth, you're a hero in this channel dude
This link has examples where buttons do not timeout: https://github.com/Rapptz/discord.py/blob/v2.0.1/examples/views/persistent.py
Yep
Self host
Not sure how things work in pycord - but perhaps they have example about it in their repository
how?
Just run it on your machine
If you have spare hardware on which you can run it, better do it
in the background forever?
Preferably so
bru
get raspberry pi
what about heroku
If you trust AWS, you can use their free tier
heroku doesn't offer free tier - after this month
bruuuuuuuuuuh
Just invest 3-5$ per month into some vps and y can run multiple bots
not a fan of paying
I use Vultr and it's running 10 bots
Have the customer pay for the hosting
xD
ight
That's actually really smart - my hosting fee is 10$ but I ask each client 15$ xD