#discord-bots
1 messages ยท Page 977 of 1
that's enough to run a full instance of VSCode on the server
Haha ofc
that's gonna be useful
Very
I used to use VSC on 4 GB RAM with Windows 10
im using on 2gb ram :D now
Specifically domains, load balancers
aha they do have a load balancer
someone can help me?
They want to get yr cc info ๐
There's probably a bunch of fine-text things you might want to read
Before you get charged for something you didn't know
Well, two of my friends are using the same to host their bots
One of them has been using since a few months now and Raven using it since like 2 months or smth
i mean oracle is pretty trusted, and the only other options i know of are AWS and linode, and they offer nowhere near the value of oracle
Please help
Ignoring exception in on_message
Traceback (most recent call last):
File "/data/data/com.termux/files/home/codes/otaku/venv/lib/python3.10/site-packages/discord/client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "/data/data/com.termux/files/home/codes/otaku/extensions/afk.py", line 47, in afk_listener
await in_afk_check(message)
File "/data/data/com.termux/files/home/codes/otaku/extensions/afk.py", line 34, in in_afk_check
data = json.load(f)
File "/data/data/com.termux/files/usr/lib/python3.10/json/__init__.py", line 293, in load
return loads(fp.read(),
File "/data/data/com.termux/files/usr/lib/python3.10/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/data/data/com.termux/files/usr/lib/python3.10/json/decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 3 (char 2)
Show yr JSON
it was given extra data
Nvm its discord
{}
Weird
code:
from discord import app_commands
from datetime import datetime
from typing import Optional
import discord
import config
import json
@app_commands.command()
async def afk(interaction, note: Optional[str]):
if note is None:
note = 'No note provided'
with open("databases/afk.json", "r") as f:
data = json.load(f)
user = interaction.user
data[user.id] = note
if 'AFK' != (user.display_name).split()[0]:
nick = "[AFK] " + user.display_name
try:
await user.edit(nick=nick)
except:
pass
await interaction.response.send_message(
f"Added to AFK list ; Note : {note}", ephemeral=True
)
with open("databases/afk.json", "w") as f:
json.dump(data, f, indent=4)
async def in_afk_check(message):
with open('databases/afk.json', 'r') as f:
data = json.load(f)
if message.author.id in data.keys():
await message.author.reply('Welcome Back!')
del data[message.author.id]
name = (message.author.display_name).split()
if "[AFK]" == name[0]:
await message.author.edit(nick=''.join(name[1:]))
with open("databases/afk.json", "w") as f:
json.dump(data, f, indent=4)
async def afk_listener(message):
if message.author.bot:
return
await in_afk_check(message)
async def setup(bot):
bot.tree.add_command(afk, guild=config.guild)
bot.add_listener(afk_listener, 'on_message')
Weird
๐
just don't use json๐ฅบ
seems you're writing to it correctly, double check that you're looking at the right file
also message.author.reply() should be message.reply()
!json
When using JSON, you might run into the following error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
This error could have appeared because you just created the JSON file and there is nothing in it at the moment.
Whilst having empty data is no problem, the file itself may never be completely empty.
You most likely wanted to structure your JSON as a dictionary. To do this, edit your empty JSON file so that it instead contains {}.
Different data types are also supported. If you wish to read more on these, please refer to this article.
nevermind that, it seems a different error
.
I need help for urm... anti spam detection
why are you even using json? use an actual database like sqlite or postgresql and just use there async bridges so it would be aiosqlite and asyncpg
Ik
It's just one small server
well in the class you pass an instance of your bot objecr which then yoy make an instance variable so it would be self.bot.remove_command()
and just use the kwarg
!d discord.ext.commands.Bot.help_command
The help command implementation to use. This can be dynamically set at runtime. To remove the help command pass None. For more information on implementing a help command, see Help Commands.
still doesnt change the fact that json isnt a database.
anyone here can help me i got stuck making my bot
its not in the class indent it
I could have rather used a txt file for such thing if it wasn't for the note
Yes
Rly hes playing minecraft
import discord
from discord.ext import commands
class CogOwner(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.remove_command('help')
@commands.command()
async def help(self, ctx):
embed = discord.Embed(title='**๐ | __Commands List__**\n\u2800', color=0x2F54C7)
await ctx.send(embed=embed)
Bruh
under self.bot = bot ?
Ye
you do know that writing in any type of file doesnt mean its a database. a txt is for text not for storing data.
!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
ok so i am making a discord bot with python and i am trying to get it to post a help page in embed but the code just wont work and its not showing any error. i can paste the code here
show code
If I keep it in database folder it doesn't mean it is a database
Are you subclassing HelpCommand?
Lol
seeing your setting and selecting data? same purpose isnt it?
bro i dont understand where I must to put self.bot.remove_command('help')
i called it command list not help so idk but its sorta like a help thing
Every fellow help command creater be like.
I give up
just add 4 spaces
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#help-commands refer to this for more info
alr
its quite easy to use a database you just install aiosqlite which is a library you can read there docs and down the sqlite browser which can make things much easier for you
Use an ORM ๐ฟ
like that?
what is pyright
a type checker
Listen
In ur bot var
it screams errors at you
Put help_command=None
And remove this
what if i dont want to make a help command just put an embed up that tells you all the commands u could use
cause my embed aint working
this is my code
async def Embed(message):
if message.content.startswith('c.commandlist'):
embedVar = discord.Embed(title='Help', description = 'commands', color=1)
embedVar.add_field(name='c.intro', value='introduces you to the settler', inline=False)
embedVar.add_field(name='c.start', value='Builds your first settlement', inline=False)
embedVar.add_field(name='c.gather', value='gathers resources', inline=False)
await message.channel.send(embed=embedVar)```
just subclass the help command
hey guys so i have this issue on iphones
?
Its discord bots not i phone support
sparky you dork
i was gonna ask if anyone has run into the problem and if they found ways around it
i.e. moving the file to an embed box
..
is very much a bot problem
I cant understand
hold on ill edit the video so i can send it
Ok.
Can someone here please mabye type a functioning embed code that works and paste it here?
I need to see what i did wrong in mine
Show ur code?
Uh wair i get it
async def Embed(message):
if message.content.startswith('c.commandlist'):
embedVar = discord.Embed(title='Help', description = 'commands', color=1)
embedVar.add_field(name='c.intro', value='introduces you to the settler', inline=False)
embedVar.add_field(name='c.start', value='Builds your first settlement', inline=False)
embedVar.add_field(name='c.gather', value='gathers resources', inline=False)
await message.channel.send(embed=embedVar) ```
Ok so whats the error
there is no error message
Huh?
just the bot doesnt respondt
Does the event trigger
well i type the message but no response
Not sure what is that
Cool game
embed = discord.Embed(title="uwu", description="the most uwu embed in the world", colour=discord.Color.blue())
embed.set_thumbnail(url="SOME URL")
embed.set_image(url="SOME URL")
embed.set_footer(text="uwuest footer", icon_url="SOME URL HERE")
embed.set_author(name="uwu name", icon_url="SOME URL", url="SOME URL")
embed.add_field(name="uwu field name", value="uwu value", inline=False)
embed.insert_field_at(0, name="field at uwu name", value="field at uwu value", inline=False)
thanks, has anyone ran into this though 
thank you so much
on every other device it just shows a loading symbol for a fraction of a second
on iphone it likes to shake the previous image in your face
*remember that all those methods are optional
hey so ive asked about this multiple times, how do i make a command where when used with a word or phrase after it it will add the word or phrase to a list in a json file
Where do u guys get pfp from
gib example
ok
alright i better go to help channels 
I also need 1 
!ot
Off-topic channel: #ot2-never-nesterโs-nightmare
Please read our off-topic etiquette before participating in conversations.
ok so if i said !list add [word or phrase] it would add the word or phrase to a list in a json file, and if i said !list remove [word or phrase] it would see if that word or phrase is in the list and remove it
its your client
I mean, why use json?
use a proper db
idk is there a better way?
i know it's their client but how do i make it stop
dm discord๐ณ
it's beyond distracting
yeah, use sqlite/postgreSQL
or mongoDB (json-like)
๐
and use their async bridges!
i'm kinda shocked no one else has had the same issue here
maybe discord hates you๐
i wonder if it happens on all iphones or specific models
this is a beta testers client
no as in a beta tester for the game
they have a regular discord client as far as im aware
has anyone else found this thing with iphones though
i can just ignore it if it's an edge case
has it happen everytime?
What happened
yeah it happens whenever the image changes
oof
it makes the image do that shaking thing
the client has a stroke
O
definitely 7 if you follow order of operations in python
It should be -1
multiplication first
BODMAS
wait
Yea
๐
!e print(2-2*3+3)
@dull terrace :white_check_mark: Your eval job has completed with return code 0.
-1
Can we take this to an ot channel now?
hunter bad at math๐
Stop it
No๐ก
Let's keep it OT please
Hello! I have an error where I restart my bot I cannot pull the warnings from a user. Why is that?
(I mean on-topic, not off-topic)
Can we see where you're defining member_id?
Should look like this:
member_id = ...
How can I fix it?
Cause I have 3 lines in the warn file
Where are you defining lines?
Should look like
lines = ...
Right here
Looks like the file might be empty
No???
Also should probably be using a database for this
I do not think this will be used much so no need to set up a database
Would still solve most issues relating to reading/writing
Sine doing that manually is always tricky
Could it be this that is causing it?
Something's going while trying to readlines() and it's not giving an error to clue us into as what might be going wrong
I doubt it
It does
100%
@client.event
async def on_ready():
async with aiofiles.open("ticket_configs.txt", mode="a") as temp:
pass
async with aiofiles.open("ticket_configs.txt", mode="r") as file:
lines = await file.readlines()
for line in lines:
data = line.split(" ")
client.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]
print(f"{client.user} is online and ready!")
await client.change_presence(activity=nextcord.Activity(type=nextcord.ActivityType.watching, name=f"for s!help"))
client.uptime_start = time.time()
client.reaction_roles = []
for guild in client.guilds:
client.warnings[guild.id] = {}
async with aiofiles.open(f"{guild.id}.txt", mode="a") as temp:
pass
async with aiofiles.open(f"{guild.id}.txt", mode="r") as file:
lines = await file.readlines()
for line in lines:
data = line.split(" ")
member_id = int(data[0])
admin_id = int(data[1])
reason = " ".join(data[2:]).strip("\n")
try:
client.warnings[guild.id][member.id][1].append((admin_id, reason))
client.warnings[guild.id][member.id][0] += 1
except KeyError:
client.warnings[guild.id][member.id] = [1, [(admin_id, reason)]] ```
@sick birch This is what is in my on_ready event
Bro
Yeah?
I, uhhh
text file...
Not that, but yea that too
Did I forget to indent the open lines of the guild_id.txt files?
Must be
Too much code in on_ready
There's so much that can go wrong there, oh my
Well the console says:
this makes me wanna cry myself to sleep
๐
the variable was referenced before it was assigned
member_id is a variable that was assigned after that reference
!e
def a():
print(a)
a = 1
a()
Yea
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | File "<string>", line 2, in a
004 | UnboundLocalError: local variable 'a' referenced before assignment
if lines is empty the code in the for loop won't be executed
So that needs to go under the try lines ๐
and have you considered using a light database or even pickle
It's going to be almost impossible to find the root cause of the issue with that much error-prone code
It could really be coming from anywhere
Or be coming from 20 levels deep
Yea I cannot seem to find it's cause Hmm
So could it be coming from my warn command?
client.command()
@commands.has_permissions(manage_messages=True)
async def warnings(ctx, member: nextcord.Member=None):
if ctx.author.id in blacklist:
bl = nextcord.Embed(title="You are blacklisted!", description="You have been blacklisted from Slytherin!", color=0xff0000)
bl.set_footer(text=footer)
bl.timestamp = datetime.now()
await ctx.send(embed=bl)
else:
if member is None:
return await ctx.send("The provided member could not be found or you forgot to provide one.")
embed = nextcord.Embed(title=f"Displaying warnings for {member.name}", description="", colour=0x003fff)
try:
i = 1
for admin_id, reason in client.warnings[ctx.guild.id][member.id][1]:
admin = ctx.guild.get_member(admin_id)
embed.description += f"**Warning {i}** given by: {admin.mention} for: *'{reason}'*.\n"
i += 1
await ctx.send(embed=embed)
except KeyError:
await ctx.send("This user has no warnings.")
This is the command that will not let me pull their warnings.
I think I found the error
It has to be in this coming from this command
so i want to make my bot status was watching then {amount of lines in a text file} any ideas how I would?
Sure. At the start of your code, fetch all necessary data (in your case # lines of a text file), then pass that in to your bot's constructor
def get_lines():
# return num of lines in a text file
bot = commands.Bot(activity=discord.Activity(...))
I opened them in the on_ready event
You shouldn't be doing that in on_ready
Why would I need to open them again
It can be the cause of all sorts of weird issues
ye
so would have to do filefile = open('list.txt')
fnum_lines = sum(1 for line in filefile)
filefile.close()
or summit like dat
then for bot status
Yeah that works. Since this is pre-bot-start it's fine to block
{fnum_lines}
You don't want to do that after your bot starts, however
or just len(lines)
Anytime
@slate swan what r yr intents
^^
I fixed it ๐ฅฒ
^ @frozen patio
@bot.command()
async def status(ctx, user: discord.Member):
await ctx.send(user.activities[0].name)```
whats the best db for python bots?
their really isnt a best db. Postgresql is for a server database and Sqlite is used for saving the data in a file, but if you want a non sql db just use mongodb
i want to do like small games
somthing simple bc i yet to learn how to use db
well i would use sql. as theirs many databases based on the language sql like sqlite for maybe learning and saving data on a file and if your bot gets bigger you could use a database on a server like Postgresql which also is based on sql.
ok then ill try using sqlite, do you have any recommendations for learning on how to use it, like website or a video?
To learn sql use: https://sqlbolt.com
Then just use the aiosqlite module: https://aiosqlite.omnilib.dev/en/latest/
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
and to see data in a ui just use the sqlite browser
ok tysm
๐
annoying bug i can't work out
have you tried other clients?
@client.event
async def on_button_click(interaction):
data = await interaction_common(interaction)
if not data:
return```
so a cooldown is in `interaction_common` if it triggers then the function returns `False` which stops `on_button_click` proceeding
but it seems to retry it when the cooldown is over?
`disnake.errors.InteractionResponded: This interaction has already been responded to before`
It seems to not fail to interact when i hit a button while on cooldown, but it doesn't proceed and do anything
it should be giving the little error this interaction failed or whatever
it seems to be literally saving every button push while on cooldown and retrying as soon as the cooldown is over and gives me the same error for each one
โค๏ธ
i guess i could do a check at the start of every single interaction to see if it has already responded but that seems wasteful
color=self.log_channel.guild.get_member(after.id).colour,
AttributeError: 'NoneType' object has no attribute 'colour'
I keep getting this error
Code:
@Cog.listener()
async def on_user_update(self, before, after):
if before.name != after.name:
embed = Embed(title="Navne Skifte",
colour=after.colour,
timestamp=datetime.utcnow())
fields = [("Fรธr:", before.name, False),
("Efter:", after.name, False)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await self.log_channel.send(embed=embed)
if before.discriminator != after.discriminator:
embed = Embed(title="Discriminator Skifte",
colour=after.colour,
timestamp=datetime.utcnow())
fields = [("Fรธr:", before.discriminator, False),
("Efter:", after.discriminator, False)]
for name, value, inline in fields:
embed.add_field(name=name, value=value, inline=inline)
await self.log_channel.send(embed=embed)```
I heard that if i ask async questions in here i will get roasted, is that true? ๐
this is driving me crazy
it's literally resending the button info up to 30 seconds later after a cooldown disnake.errors.InteractionResponded: This interaction has already been responded to before
it definitely hasn't responded already
and it shouldn't be doing anything after being returned
no you wont. if its not fitting to discord bots go to #async-and-concurrency
Why is my bot doing this after I restart it?
where are you saving the warnings?
in a .txt file
well thats the reason
you dont use a .txt file as a database
It is actually!
project = "ExoWorlds"
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
if message.author == self.user:
return
async def get_exo_floor():
s = AsyncHTMLSession()
r = await s.get('https://exoworlds.io/marketplace')
await r.html.render(wait=3, retries=5, reload=True, sleep=2)
soup = await BeautifulSoup(r.html.html, "html5lib")
c = await soup.find('div',attrs={'class':'marketplaceStats__item'})
print(c.text)
exo_floor = c.text
return exo_floor
async def background_task():
await client.wait_until_ready()
while not client.is_closed():
await asyncio.sleep(5)
exo_floor = await get_exo_floor()
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
#change name of discord channel
voice_channel_2 = client.get_channel(964211130627162192)
await voice_channel_2.edit(name="Exo MP Floor: " + str(exo_floor))
print(current_time + str(" Exo Floor updated to ") + str(exo_floor))
client = MyClient()
client.loop.create_task(background_task())
client.run(token)
When i run this i always get
Task exception was never retrieved
future: <Task finished name='Task-1' coro=<background_task() done, defined at C:\Users\Alex\Desktop\exo_role\role_bot-main\src\asynctest.py:38> exception=RuntimeError('This event loop is already running')>
Traceback (most recent call last):
File "C:\Users\Alex\Desktop\exo_role\role_bot-main\src\asynctest.py", line 44, in background_task
exo_floor = await get_exo_floor()
File "C:\Users\Alex\Desktop\exo_role\role_bot-main\src\asynctest.py", line 30, in get_exo_floor
await r.html.render(wait=3, retries=5, reload=True, sleep=2)
File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\site-packages\requests_html.py", line 598, in render
content, result, page = self.session.loop.run_until_complete(self._async_render(url=self.url, script=script, sleep=sleep, wait=wait, content=self.html, reload=reload, scrolldown=scrolldown, timeout=timeout, keep_page=keep_page))
File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 622, in run_until_complete
self._check_running()
File "C:\Users\Alex\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 582, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
and i have no idea how to fix that. I tried to import nest_asyncio and apply it but this would just never return anything at all
as the file extension shows its for text and not saving data
It is only storing 4-5 warns
why are you subclassing client and the errors says it
Thats just a tiny snippet out of over 1k lines of code
but the only thing thats relevant right now for this issue
Well the error quite says it.
Yeah
Maybe iยดm just an idiot then, still stuck
There has to be a way
use a db i.e sqlite
I could use sqlite3
Maybe if I open the file in the warning command :0
aiosqlite, yes
Itโs also much less error prone and easier to troubleshoot
cause they actually handle errors๐ณ
Yes
But there has to way to pull a .txt file
to get the data after you restart the bot
Probably in setup hook
@sick birch btw any new news on the new thread for the channel?
or just create a task with the AbstractEventLoop
Not yet. Give us a bit
alright ๐
disnake.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
what does this mean
Your responding to an expired interaction
@client.event
async def on_ready():
client.add_view(MyView2())
client.add_view(MyView1())
client.add_view(MyView())```
Won't this stop it?
I don't see how this would be causing the issue
Just make sure if you are gonna be defering and sending followup messages, that you send it within 15 minutes
After 15 the interaction token will expire and invalidate
await interaction.response.defer()
await interaction.followup.send(f"Your ticket has been created, go to {channel.mention}", ephemeral=True)```
Why are you defering then right after sending a message?
Couldn't you just respond already without the followup
well when I do that, there are some times they will ask me to defer it
What?
I interacted with the button and the error told me to defer it so thats what I did
That;s odd, never expirenced that before
i assume its this message you're referring to: https://github.com/DisnakeDev/disnake/blob/master/disnake/errors.py#L304-L312
interesting that disnake does that
disnake/errors.py lines 304 to 312
msg = (
"Interaction took more than 3 seconds to be responded to. "
'Please defer it using "interaction.response.defer" on the start of your command. '
"Later you may send a response by editing the deferred message "
'using "interaction.edit_original_message"'
"\n"
"Note: This might also be caused by a misconfiguration in the components "
"make sure you do not respond twice in case this is a component."
)```
yes
does your unknown interaction error come up often? if its only occasional then its likely caused by internet latency
comes up often
you're creating the ticket channel before the defer right? maybe thats the bottleneck
oh
you can time it to make sure - personally i got 0.9s of delay when executing create_text_channel - and if its the issue, you should place the defer at the start, do whatever you need in between, and send your followup at the end
i think your indentation is a bit messed up
the else clause along with the line under it is underindented, while the two lines after that are overindented
btw collections.Counter would be a good tool for this
!d collections.Counter
class collections.Counter([iterable-or-mapping])```
A [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") is a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict") subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The [`Counter`](https://docs.python.org/3/library/collections.html#collections.Counter "collections.Counter") class is similar to bags or multisets in other languages.
Elements are counted from an *iterable* or initialized from another *mapping* (or counter):
```py
>>> c = Counter() # a new, empty counter
>>> c = Counter('gallahad') # a new counter from an iterable
>>> c = Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args
also you dont need to fetch every user, the Member object itself can be used as the dict key
you also have the members intent enabled, right oops you dont need it here
when I run my code I get this error, and I have no idea how to fix it
hikari.errors.UnauthorizedError: Unauthorized 401: '401: Unauthorized' for https://discord.com/api/v8/gateway/bot
It was working a while ago, but I needed to update my client secret so I think that is causing the problem, but I have no idea how to fix it
you need to regenerate your token and copy it from the application page
maybe, if your config somehow didnt get updated to include the new token
do you want me to send the full error message?
wait i think i know why
nevermind
I have no idea
try printing your token when you pass it into the bot to make sure its the correct one you're expecting
the error is coming from bot. run
which does reffer to the defined token
bot = lightbulb.BotApp( token='', default_enabled_guilds=(), prefix ="$", intents=hikari.Intents.ALL )
is there still a way to print it even if it is deffined in the variable?
oh if you hardcoded the token then nevermind printing it
what you wrote there is a long string of random letters/numbers right
then maybe your script didnt update with the new token when you tried running it?
it isint a docker problem because it still breaks outside of docker
oh ok
yeah thats what im thinking

still doesn't work
so i am trying to make it so that if a message is sent by a certain person it replies with something but i am getting this error
@bot.event should be written without the parentheses, and also bot.send_message() is extremely outdated; text channels have a send() method so you would be writing await message.channel.send(...) there
ok thanks
oh and the IDs are represented as integers instead of strings
thanks let me do that real quick
see here for up-to-date documentation: https://discordpy.readthedocs.io/en/stable/quickstart.html
examples on the discord.py repository: https://github.com/Rapptz/discord.py/tree/v1.7.3/examples
^ both of these are for version 1.7.3
i have been reading the old ones all this time
Just use ctx.send
oh lol, the same site still hosts the legacy documentation
how would I get the ID of a recently created channel? I have the snippet of code await guild.create_text_channel("hello world"), but I would like to get the ID of it. How would I do that
create_text_channel returns a TextChannel object, so you can access the .created_at property right afterwards
k thx
oh wait, i dont know why i said .created_at
yeah
i was confused lmao
I was looking at the docs and I was thinking this cant be right
yea i just thought of it cause the created at time happens to be derived from the .id of the channel
yeah I saw the docs on it thanks btw
the on_message event only takes a Message object, so you should keep it as on_message(message)
(when you see ctx, its a conventional name used with message commands in discord.ext.commands)
you can do the same thing with the reply() method that the Message object has
ok let me try
please tell me how in discord.py do events and commands ?
that is, so that one in the file reads the other. Because event and commands don't work in the same file
@nova stag Can I help you ?
yes pls
i am planning on making discord bots, should i use discord.py or hikari?
@nova stag do you want to write to a certain participant in private messages ?
from what i have heard hikari is more stable but i am using discord.py
Make the ping into a string and check it with the message content
no like in server when it see a certain person has messaged reply in the server with something
Yes
!d help
help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.
Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).
This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
@nova stag what are you trying to do and whatโs the error
if a certain person sends a message in the chat the bot replies with something to that person in that chat
Thereโs no author
Itโs only message
!d discord.Message.mentions
A list of Member that were mentioned. If the message is in a private message then the list will be of User instead. For messages that are not of type MessageType.default, this array can be used to aid in system messages. For more information, see system_content.
Warning
The order of the mentions list is not in any particular order so you should not rely on it. This is a Discord limitation, not one with the library.
can u explain i am new to this stuff so i dont have any idea
Check if client.user is in message.mentions
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/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/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
As you can see
ohhhhh
It only takes 1 positional argument which is message
ok i get it now
well i understand that it doesnt take that argument
so what am i suppose to do now?
Use message
Remove author since it doesnโt take that
I think you should write if message.content == ping instead because if message == ping will compare the message object with a string which will always be False
because message will be a discord.Message object
@nova stag
Noice
Why are you naming your id variable ping
thats something i came up with at that time
no particular reason
you don't have to always specify things to variables unless you're going to be changing them or using them more than once
you could also do if message.author.id == ..:
is there an event similar to on_ready that sends a message when the bot is stopped
https://discordpy.readthedocs.io/en/master/api.html#discord.on_disconnect you could use this
Anyone?
@regal flame you should subclass and override close
what does that mean?
class MyClient(discord.Client):
async def close(self):
# call super().close and do your logic
Do I just type "super().close"?
i was doing that before but was getting errors so yeh did this and it worked
what was the error?
on_messege missiing 1 positional argument "message"
import commands
yeh
commands
import discord, random, aiohttp, asyncio
from discord import Webhook, AsyncWebhookAdapter
from discord.ext import commands
from discord.ext.commands import commands
from colorama import Fore as C
from colorama import Style as S
then delete the 4 the line
need help
or keep it
from colorama import Fore, Style
delete
how can i delet a messege sended with the bot ?
you can use the delete_after kwarg in the send method
I have to make new repl when I code with friends
The API times out on repl
ahh ok
It doesnโt do that in my host or VS Code ๐
same using VS never got that error
btw
u shouldnt send your bot token like that in chat
i would suggest u to regenerate it
Itโs not even the token
someone can use it to take over ur bot
All tokens have an O at the beginning
ooo didnt know that
then what is that and why is his variable named token
So yea they all start with O
same but yeh i didnt knew thats always the case
Good question ๐
And how do you import discord in the from discord.ext.commands line
Itโs already imported
i was thinking that when i saw it well i guess he is super new
Yeah
for the event on_message how do I get the channel that the message is sent in?
thats a gift from replit for using their service :)
Ikr
Yo thanks for using repl take our API timeout ๐
On mesage takes message not ctx
ctx.channel is correct here
Is it possible to have a bot send a picture. When the picture is sent it will have around 5 reactions added by the bot. I want it to be where the user can click 2 reactions and the combination will send a gif. Is this possible and if anyone knows how please help 
Hmm
well, you can name te argument anything
Oops forgot, my brain is dead atm i got no sleep
I do not think a bot can add 5 reactions.
Its definitely possible lol
It is
My bot does it but Iโm lost along the lines of when the user reacts to two of the reactions and It sends a gif
5 separate emojis?
Yes
Yeah
Ohhhh I thought he meant 5 to 1 emoji ๐
Iโm assuming if I get the first down itโll be a whole bunch of elif statements
Ah
I have this right now:
channel = client.get_channel("CHANNEL_ID")
if message.content.lower().startswith('experiment'):
moji = await message.channel.send("https://media.discordapp.net/attachments/955441795209236530/962094246314254437/unknown.png?width=480&height=612")
emoji = ["\N{Large Yellow Circle}", "\N{Large Green Circle}", "\N{Large Blue Square}", "\N{Large Red Circle}", "\N{Large Blue Circle}"]
for experiment in emoji:
await moji.add_reaction(experiment)```
uhhhh, thats gonna be a lot if work
# first you gotta send the file with
msg = await send(file=discord.File("filename.png")
#add reactions
for reaction in ("reaction1", "reaction2", ...):
await msg.add_reaction("reaction")
#check for reactions
def check(message):
...
ev = await Bot.wait_for("reaction_add", check=check)
#PROCESS FURTHER
that totally is up to you
Where are the examples to discord.ui.modals
in the gist that danny released regarding continuation of dpy
idh the link at hand rn
Oh ty
here's an example - https://github.com/Rapptz/discord.py/blob/master/examples/modal.py
Tyty this helps sm
its alright lol
I got buttons down i just needed some help with modals and textinputs
moji = await message.channel.send("https://media.discordapp.net/attachments/955441795209236530/962094246314254437/unknown.png?width=480&height=612")
emoji = ["\N{Large Yellow Circle}", "\N{Large Green Circle}", "\N{Large Blue Square}", "\N{Large Red Circle}", "\N{Large Blue Circle}"]
for experiment in emoji:
await moji.add_reaction(experiment)
if user.reaction.emoji == "\N{Large Yellow Circle}" and "\N{Large Green Circle}":
await message.channel.send("https://media.discordapp.net/attachments/957163963588681788/957164412807036928/yg.gif")```
I'm getting an error: "user" isn't defined. Does anyone know if I'm on any right track with making the bot send a gif if 2 reactions are clicked?
This is now the error:
line 57, in on_message
if discord.Member.reaction.emoji == "\N{Large Yellow Circle}" and "\N{Large Green Circle}":
AttributeError: type object 'Member' has no attribute 'reaction'
use a wait_for
Where do I put that? ;-;
Oh yeahhh
k might've got it
smth lile this
async def on_message(message):
if message.content.startswith('$thumb'):
channel = message.channel
await channel.send('Send me that ๐ reaction, mate')
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '๐'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('๐')
else:
await channel.send('๐')โ
So like they need to react to two reactions in order for the bot to send the message
yeah, will need 2 wait_for
Oh jeez! Yeah that's the better option haha! Thanks lol and have a good sleep
Oh okay!
I apologize for leaving while helping
Nahhh you good hahah
what can I do to make it so any message that is sent through DMs to my discord bot is sent to me through DMs
you should be able to receive dms through the on_message event
should be able to check if it's a dm with if message.guild is None
Hey people! I'm having an issue with my bot. I want the bot to send an image with reactions. When the user clicks 2 of the reactions the bot will send a gif. I have 5 reactions total so there are a lot of combinations. The issue I have now is that the bot is able to send the image with the reactions but when I click the two reactions nothing happens... Here is my code if anything can help โค๏ธ
async def on_message(message):
if message.content.lower().startswith('thumb'):
channel = message.channel
moji = await message.channel.send("https://media.discordapp.net/attachments/955441795209236530/962094246314254437/unknown.png?width=480&height=612")
emoji = ["\N{Large Yellow Circle}", "\N{Large Green Circle}", "\N{Large Blue Square}", "\N{Large Red Circle}", "\N{Large Blue Circle}"]
for experiment in emoji:
await moji.add_reaction(experiment)
def check(reaction, user):
return user == message.author and str(reaction.emoji) == '\N{Large Yellow Circle}' and '\N{Large Green Circle}'
try:
reaction, user = await client.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await channel.send('https://media.discordapp.net/attachments/957163963588681788/957164412807036928/yg.gif')```
*Not getting any errors
Has anyone every had a issues where a discord bot changed your loggers os time?
(it is a very strange issue I am dealing with now)
so if i use the on_message thingy
all other commands stop working why is that?
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageโs author is a bot and doesnโt call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
Use a listener
Hello SIr
Any one
I am creating discord sever joining script but when I send reqeuest with captcha key discord responsed that your captcha key required
Looks like you have been banned from accessing the API
The little snippet you showed is the cloudflare stuff
Usually when you start seeing HTML in your python errors, it's your cue to get off replit

Someone help me
Any one know about it?
Help me
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Show full traceback
Kind of difficult to tell what the issue is from a large chunk of seemingly random characters
Seems like you're getting ratelimited, try kill 1 in shell and restart the repl, sidenote: you'll keep facing this issue if you use replit
You printed the r.text which will print all the response content, also this doesn't seem like a bot account~
Defiently malicous
Since bots can't join a server using invites
I have read discord official APIs
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
I am creating a python script
the API doesn't allow bots to do that, that's for a normal user side.
Okay
even if you're doing it for a bot, that won't work
if you're doing that for a user, that's against ToS since automatic a user account in any way is not a good idea
VS Code and my host does not do that LMAOOOOOOOOOOO
Actually, it depends more on your network system than your IDE, replit uses shared Ips so one of the user on that IP will let others get ratelimited too
However, if you go through the Oauth2 framework, you can get an access token for a scope guilds.join, that will allow bot to make the correspondng user join a guild
That is a valid option, albiet it isn't easy to setup
oh i see,
But still not with an invite right?
Yep, still not with an invite
You have to make a request via PUT /guilds/guild_id/members/user_id
So thats how this thing works ๐ค
Yikes, quite the invasive bot
Trying to work around a captcha is not appropriate for this server. The captcha exists to prevent automation, and we won't help with that.
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
wait bots can do that
Oauth, yes
Indeed
@bot.command()
async def me(ctx):
member=ctx.author
role = discord.utils.get("959611774498390127", id = "963371714606149644")
for member in ctx.guild.members:
if role in member.roles:
print('Supporters') ```
bro this isnt working what is wrong with it
do you have the members intent enabled?
yes
mind showing your intents?
i show 1min
sure
oh i found the problem,
you are defining member as the author of the command and using member variable to iterate through the guild members, change one of their names, and discord.utils accepts an iterable as its first argument so you need to have the guild roles to iterate, and the id should be an integer
Why ppl use a var to define ctx.author :/
member is already a thing, it just confuse
uh Sure.
Intents*
utils.get takes an iterable as its first argument, not a string
On ur code ig
how do i get the white box?
@granite parcel
And unlike discord.js, IDs in python are integers, not strings
<t:1649991837:F> like this?
yes
I think "F" is default isn't it?
idk, havent used it that much
!d discord.utils.format_dt can help you format datetime objects
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...
convert it to int
Here u can use var
?
await ctx.send(f"<t:{int(ctx.guild.created_at.timestamp())}>")```
use f strings
try now
Bruh
@buoyant zodiac use that
Let's not spoonfeed, please
But yes, that's how it should be done
Or, a more elegant solution would be to use discord.utils.format_dt()
this should work@sick birch
?
I know it should, but I'm saying not to spoonfeed
ohk
disnake.utils.format_dt(dt, /, style='f')```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)"), [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") or [`float`](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Neat
@bot.command()
async def me(ctx):
role_names = [role.name for role in ctx.author.roles]
if "Voters" in role_names:
await ctx.send('Hi')```
?
this is working but can i make it universal like if author use this cmd anywhere where the bot is it gives the reply
Wdym universal?
It is already universal
i mean if anyone use the command in any server
It does do that?
Don't you have to go through every guild the bot is in
And check if the role exists and in the author's roles
And if the author is in the same guild
every server cannot have the same role unless the bot creates one
so its pretty much useless to do it
Hi Skev
c = [member for member in guild.members for guild in bot.guilds if role in member.roles]```
idk if that works lmao (it shouldnt)
xD
The doubt


Tough twister
wouldnt work
Ye
reason?
thats not its syntax
lol didnt try
nor did I use list comps much anyway
Okimii change pfp day by day
Yup
!e
print([a for a in [b for b in range(101) if b == 54]])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[54]
Why did u nest it?
just showing how to use 2 for loops in a list comp
!e
print([a for a in range(101) if a == 54])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
[54]
which its just iterating through a list already
if b == 54
yes only if the element is 54
it prints the list if the number is 54
Oh i didnt see the print
xD
Lemme see something
Ok?
!e
a = 64
match a:
case 63:
print("lool")
case 64:
print("noo")
case _:
print("suii")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
noo
stop going offtopic
Suggest more topics here!
stop
#bot-commands
@slate swan @slate swan #bot-commands
/ban
๐ณ
๐lmao do yall add user commands to your bots?
Cause I don't really like them~
you guys have commands?
i use events๐
Huh
you guys using Gateway?
nah i just yeet them to the api hoping they handle it i dont event acknowledge hearbeats
You need to use the same, in order to make yr bot come online

ever heard of a joke hunter?๐ก
Uhh
..
True
smh hun๐ก

but what if all I want to do is spam "hail okimi" in a channel, ๐๐คฒ I'll just go for a rest client
๐
i wouldnt care
because its not aimed at me
my name is okimii not okimi get it right 
okay me
smh sarthak you know better๐ก
Take this to an ot channel please
can i take you with me to #ot1-perplexing-regexing ๐ฅบ
import discord
from discord.ext import commands
bot = commands.bot(prefix="^")
@bot.command(name="spam")
async def okimii(ctx):
while True:
await ctx.send("hail okimi")
bot.run("*oahs9whhโนjยฃร*ร9โฌ8hisosiw028293dndmxlzla0a9")
misspelled my name๐
*import
I do that usually, eval stuff
use semi colons and make it a one liner ๐ณ ๐
@(bot:=getattr(getattr(getattr(__import__('discord'),'ext'),'commands'),'bot')(prefix='^')).command(name='spam');async def okimii(ctx): [await ctx.send('hail okimi') for _ in iter(int, 1)];bot.run('token')
Yo
Please don't leak #esoteric-python into other channels

doesn't work
Hello is anyone available to offer any advice? I've got a loop, which works perfectly but only the first I run the code.
When the loop comes back round it doesn't seem to do as it should which is retrieve the data from the SQL DB
Can anyone shed any light to what im doing wrong?
https://paste.pythondiscord.com/butaritawo
I've posted the actual loop itself. any help would be greatly appreciated.
Could it be because im using aysnc tasks
What even is esoteric python
The type of Python that a normal human can't understand. It requires super natural powers to understand
So
The chaotic evil dudes
Yes
Yeah one look at the channel i've got no clue what the fuck is going on
Don't go in there, unless u wanna start questioning your decision of learning Python
I am
Hi
What the fuck is this voodoo magic
How do i get my slash commands to work in one guild not global
discord.py 2.0
@ me plz
u can use a check
!custom-check
Custom Command Checks in discord.py
Often you may find the need to use checks that don't exist by default in discord.py. Fortunately, discord.py provides discord.ext.commands.check which allows you to create you own checks like this:
from discord.ext.commands import check, Context
def in_any_channel(*channels):
async def predicate(ctx: Context):
return ctx.channel.id in channels
return check(predicate)
This check is to check whether the invoked command is in a given set of channels. The inner function, named predicate here, is used to perform the actual check on the command, and check logic should go in this function. It must be an async function, and always provides a single commands.Context argument which you can use to create check logic. This check function should return a boolean value indicating whether the check passed (return True) or failed (return False).
The check can now be used like any other commands check as a decorator of a command, such as this:
@bot.command(name="ping")
@in_any_channel(728343273562701984)
async def ping(ctx: Context):
...
This would lock the ping command to only be used in the channel 728343273562701984. If this check function fails it will raise a CheckFailure exception, which can be handled in your error handler.
can you make a custom on_message event where it only looks at message in one channel
Yea
@bot.event
async def on_message(msg):
if msg.channel.id == ...:
bot.dispatch("my_custom_on_message_which_listens_to_messages_only_in_one_channel", msg)
await bot.process_commands(msg)
is there a way to nnot check channel id in the event itself?
Wym
what's dispatch?
Internals
so should i be using that?
Yea
i mean like a function maybe and the event triggers the function
Uh
uh as in that was a dumb question or not sure?
Not sure
in discord.py lib how do i enable a slash command from a cog
How do I tell discord that I have seen the interaction? When someone presses a button, the command does all it needs to do, but still says that the interaction failed because I never responded to that interaction.
which lib you're using?
๐ค may i have a look at the code?
@discord.ui.button(
label = "L",
style = discord.ButtonStyle.green,
row = 0
)
async def leftTrigger(self, interaction: discord.Interaction, button: discord.ui.Button):
pyautogui.keyDown("A")
await asyncio.sleep(0.2)
pyautogui.keyUp("A")
embed = fmte(
ctx=self.ctx,
t="Playing: Pokemon: Fire Red",
d="For: {} minutes".format((time.time() - self.ctx.start_time) / 60)
)
pyautogui.screenshot().save("pyauto_resources/game_image.jpg")
file = discord.File("pyauto_resources/game_image.jpg", filename = "Game_Image.jpg")
await interaction.message.edit(embed=embed,attachments=[file,],view=VBA_View(self.ctx,self.bot))
``` Each message has 9 buttons. When a button is pressed, the message changes to new game frame and new time log.
Nothing is said to the user
btw btw.. that failed thing.. because u never responded is like.. idk if this is the case.. but like.. there is timeout thing in buttons ok.. so if it gets timeout then interactions don't work
yeah I want to tell discord to not expect anything
and that the interaction is complete
btw I know that I can use self.ctx.defer(), but that just keeps the interaction going forever, which isn't what I want
then..on timeout, u can edit the embed, by sending the 'view' again
it'll be a new interaction.. but for the user it'll be just like an edit message..
I could, but I just think it's much more clean to edit. If I find no other solution, then sure I'll do that.
.. for user it'll be just like an edit mesage...
welll.. tias :'/
I'm trying to make a music bot but this happened. Can anyone help me?
Context doesn't have a voice_bot attribute, perhaps you wanted voice_client?
!d discord.ext.commands.Context.voice_client
property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
i've used asyncPRAW to make sure that my meme command will be asynchronous, but it doesn't appear to be so. when i run the meme command, it takes a few seconds and then sends the meme. if i try to run any commands in those few seconds, it does not respond to them.
reddit = asyncpraw.Reddit(
client_id=db["reddit_id"],
client_secret=db["reddit_secret"],
user_agent=db["reddit_agent"],
username=db["reddit_username"],
password=db["reddit_pwd"]
)
class memes(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name="meme", description="Sends you a meme. Default subreddit is r/memes. You can also specify a subreddit.")
@commands.cooldown(1, 6, commands.BucketType.user)
async def memeFromReddit(self, ctx, subreddit="memes"):
try:
subreddit = await reddit.subreddit(subreddit, fetch=True)
if subreddit.over18:
await ctx.send("ohoho you sneaky little bastard, that's an nsfw subreddit")
return
subs = []
async for submission in subreddit.hot(limit=30):
subs.append(submission)
sub = random.choice(subs)
while True:
if sub.id not in db['usedSubs'] and sub.is_reddit_media_domain and not sub.is_video and not sub.over_18:
break
elif sub in oldSubs:
sub = random.choice(subs)
memebed = discord.Embed(title=sub.title)
memebed.set_image(url=sub.url)
memebed.set_footer(text=f"r/{sub.subreddit}")
oldSubs.append(sub)
db['usedSubs'].append(sub.id)
await ctx.send(embed=memebed)
except:
await ctx.send("couldn't get your meme. sorry!")
there's a chance that your while loop is freezing the entire thing?
you might want to also check if any of the properties you're getting are making extra requests
Hello is anyone available to offer any advice? I've got a loop, which works perfectly but only the first I run the code.
When the loop comes back round it doesn't seem to do as it should which is retrieve the data from the SQL DB
Can anyone shed any light to what im doing wrong?
https://paste.pythondiscord.com/butaritawo
I've posted the actual loop itself and also the first function. any help would be greatly appreciated.
Could it be because im using aysnc tasks
is there a way to make a command set an embed colour? (i already made the db)
like
!embed set color ffffff
im using
emb = discord.Embed()
emb.description="<< **This is how the color looks like**"
emb.colour = "0x" + value
await ctx.send(embed=emb)
but it gives an error:
Ignoring exception in command e_embed edit:
Traceback (most recent call last):
File "/home/runner/ganyubot/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/ganyubot/commands/embed.py", line 164, in edit
emb.colour = "0x" + value
File "/home/runner/ganyubot/venv/lib/python3.8/site-packages/discord/embeds.py", line 230, in colour
raise TypeError('Expected discord.Colour, int, or Embed.Empty but received %s instead.' % value.__class__.__name__)
TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
Am facing a strange issue I have a bot which has some NSFW commands on a particular server it is serving those commands in SFW channel while on every other it aint
nsfw commands are allowed only in NSFW channels
the error is speaking 
no i mean is it possible
oh its not
oh, how though/
read the error 
so...? it is not hard to guess it is literally written 
you know not all ppl have ur level of intelligence 
im still learning
bruh it's not like intelligence or something is basic python, basic like the lowest level possible 
i mean i understand the error
TypeError: Expected discord.Colour, int, or Embed.Empty but received str instead.
Embed.colour takes as type Union[discord.Colour, int, Embed.Empty]
You are assign it to a string
if your use discord.Colour, you can set an RGB value
!d discord.Colour
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)").
There is an alias for this called Color...
Embed.colour = discord.Colour(255,255,255) for example shall return white
oh makes sense now
Hi there, just looking for tips, I am currently moving from json to sqlite3, and after adding a connect and a cursor in my on_ready I realized that if I put a value guild_id and then my other values it will just put everything on the same row. Would there be a way to create some kind of bag inside my table for a specific guild?
for every guild insert a new row 
yeah but that would mean every thing will just be in the same main table isn't that bothering ?
(I haven't done SQL in 3 years so it's hard)
create a new table for every guild ๐คทโโ๏ธ
yeah I thought about that as well
I was just wondering if there was a way to centralize everything in the same main file and then make subtable inside
no-
i was just suggesting
because I am using the connect command in the on_ready in my events cog, so I don't see a way to get the guild_id other than adding a ctx argument inside which seems weird for that function
lol bro i stopped writing after reading that 
Yeah I wouldn't try using sqlite if I had to do that
okay okay, iโm sorry if my suggestion isnโt as good as yours
no comments from my side
I never said that but ๐ญ why a new table for every server
Bro database are used to store dataset which refers to the same object (alias a same set of data)
there is absolutely no sense to create different table for every guild
So if I put everything inthe same file and then just do a FROM main SELECT guild_id it should work just fine ?
plus it will be a really mess
ok
so well
this should work ?
Just use MongoDB ๐
yeah it'll select the guild's id
oki
lol
I haven't done sql in 3 years I don't remember most of it
I never understood how to set primary and foreign keys ๐ฅฒ
๐ฅบ
๐
U can also look at deta.sh DB btw
o_O
CREATE TABLE IF NOT EXISTS tablename(
guild_id INTEGER PRIMARY KEY NOT NULL,
)
its easy as that tbh
-_-
user
