#discord-bots
1 messages · Page 1074 of 1
damn still doesnt work
im using vs code
wait
im using discord.py v2.0 @flint isle
did i leave disnake in that code
sup?
YOO
a command isn't responding in your cog, right?
Correct
does any command in your main file still respond?
Idk I made the bot only for dailyspin so I wouldn’t know ,
I only have a event in my main.py
do you have an on_message event in your main file?
can u give a code example pls
Nah a on_command_error
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.
don't leak your token
i don't undrs how
Dw mine is in config.py
can someone send me the tenor api for discord.py slap
what dpy version is this%?
?
enable message content using intents.message_content = True
damn i forgo
can u rq help me make that same command in the cog , but as a slash command
discord-py-slash-command 's pypi shows an example
sure, ill try my best, I havent worked much with dpy's slashes but ill be able to help ig
ok
checking out GOOD examples is a great starter
hey, when i host using freshping, my bot regularly goes offline
is there anything i can do to fix this?
with replit? no there's nothing you can do
fr, seeing ephemeral=True gives me the creeps now, im so rusty on dpy syntax
don't crosspost in other servers, you'll literally get the same answer
^
especially after CommandTree lol
I'm just waiting for a stable release, I don't want to migrate every breaking change weekly
im never switching back to discord.py again :kek:
well, in that case, I hope your fork outlives dpy
hikari isnt a fork.
no idea it was hikari
and making unnecessary complcations
In embed.image.url: Scheme "<response [200]>" is not supported. Scheme must be one of ('http', 'https').```
the error kinda justifies the reason
What does the error mean
r is the request object
which is supposed to be a string with http/https link
It seems like it's a GIF so you'll have to do some additional stuff to get that to work
You don't even need requests i don't think
oh
just pass in the URL to the image
they are making a search
alr
What are the methods for creating invitation tracker? Aside from comparing two old and new invitations
it is
No? it seems like an API request
it looks for a slap tenor gif
what data type does that endpoint return?, json most probably
JSON, yes
(r.json()).get('url') is what you need
What are the methods for creating invitation tracker? Aside from comparing two old and new invitations
Not quite
thanks for your tenor tokenkey btw
results is a list
oh, yeah
Something like .get("results")[0].get("url")
Kind of prone to error
But I'm guessing you know how to deal with the errors
@commands.command()
async def slap (self, ctx, member: discord.Member):
embed = discord.Embed(
colour=0xffffff)
embed.add_field(name='Slap', value=f"{ctx.author.mention} slaps {member.mention}", inline=False)
r = requests.get("https://g.tenor.com/v1/search?q=slap&key=TOKEN&contentfilter=high")
(r.json()).get("results")[0].get("url")
embed.set_image(url=r)
await ctx.send(embed=embed)```
this is what I've done so far @sick birch
aiohttp pls
yeah I already copied it so now I dont have to set up an account on tenor, smart work
(r.json()).get("results")[0].get("url") needs to be passed into the embed
Crying out for advice.. What are the methods for tracking invitations? Aside from comparing two old and new invitations
url = r.json().get("results")[0].get("url")
embed.set_image(url=url)
oh ok
you can first get him ratelimited so he stops using that key, and then you can use it personally
Aint no way that the biggest invitation tracker uses that method.. like if there are 10000 servers and each has over 10000+ users then you would need nasa computer for that
why do we always think alike-
u guys are criminals
Not really
Larger bots do have powerful hosts anyway
you can have at most 1k invites, which is very little processing time
You'll spend more time waiting on an HTTP response than processing it
Not to mention most servers don't have anywhere close to that amount of invites
discord bots in a nutshell
Lesson learned to not leak your API keys?
there's a limit to creating invites
get faster internet

i have faster internet
I'm on phone ....
sus
dw, now you can ask robin for it cause he has it in that response's headers
what
😔 did you not use his link to open that response?
i got a new key and the images are not loading
i didn't even realize it had the key until you all pointed it out
Your code might still be using the old one
lol
its not related to the key, you simply wouldnt get a response and get an error if that was the problem
@scarlet aurora dont wish for both 'high' quality image and fast image processing at the same time
discord takes time to resolve the images from other cdns + high quality gif in tenor takes to load normally
*takes more time
url = r.json
media_filter=basic
why do you need all that
don't you have the url
he is making a search using the tenor api
the api doesn't just give u the url
try printing url variable
the url
sends the gif, and it works, i can see it, it just wont open on the embed
it sends instantly
I messed up your api key.
i knew it
lmao
nvm ill just stop making weird jokes
yes ur humor is sometimes quite un-understandable when its related to API KEYS
Ashley moment
lemme try
stop
creep
wdym
@heady sluice nice bot u got there in yr About Me btw
Ik it has lots of features
And, uhhh, has anyone here used the nano command for putty SSH?
Ashley
istg I still hate Linux
I didnt check the last time i did
Jesus WebsiTeem what did you do
same thing, go on
y'all haven't read the boys of the Pal street
writing someone's name lowercase if like taking the pride of it
Eslint no-unused-vars: import discord is not used 
stay uneducated noobs
No thanks
My first question.... what is "the boys of the Pal Street" but its ot
might not have translated perfectly
yo
Disable the error using eslint disable no-unused-vars
damn everything is up to date with my bots , i only need to fix welcome system
btw @slate swan i coded the set message command , asher helped me a bit . can u check it
Bruh what is even so complicated in it 😔
@maiden fable ❤️
he's a professional checker
@commands.command()
async def set_msg(self, ctx):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT welcome TEXT FROM wm where guild_id = ?", ctx.guild.id)
data = await cursor.fetchone()
if not data:
await cursor.execute("INSERT INTO wm(guild_id, channel_id, welcome TEXT) VALUES(?,?,?)", ctx.guild.id, ctx.channel.id, 'xyz')
await db.commit()
return await ctx.send(f"Welcome message has been set!")
await cursor.execute("SELECT welcome TEXT FROM wm WHERE guild_id = ?", ctx.guild.id)
mesg = await cursor.fetchone()
if not mesg: return await ctx.send("There is no welcome message currently set.", delete_after = 10)
return await ctx.send(f"welcome message is {mesg}")```
Its fine
are u sure?
wdym, there's an error, i already spotted one
What is the error
Is this sql correct or what?
aiosqlite
don't play games with me rn, if u know the error just tell him then already got too much on my mind lately
welcome TEXT everyehere, and the INSERT line
@scarlet aurora use this as ur url variable : (res.json()).get("results")[0].get("media")[0].get("gif").get("url")
and pls dont steal my token 🥺
how could i fix this
I mean the welcome TEXT thing
idk tbf it just came into my mind .. well atleast i tried
Btw ye my table wasn’t created so I’ll show that next
It’s an error
BTW MK why u even overcomplicating stuff
await cursor.execute("CREATE TABLE IF NOT EXISTS wm(guild_id INTEGER, channel_id INTEGER, welcome TEXT, leave TEXT)")```
yea this seems cool
btw
it raises an error ( in the select)
you are creating a table, with TEXT as the data type of the welcome column
you dont need to mention TEXT in the select
@commands.Cog.listener()
async def on_member_join(self, member):
async with aiosqlite.connect("wm.db") as db:
cursor = await db.cursor()
await cursor.execute("SELECT * FROM wm WHERE guild_id = ?", (member.guild.id,))
data = await cursor.fetchone()
if data is None:
return
else:
if data is not None:
await cursor.execute("SELECT channel_id FROM wm WHERE guild_id = ?", (member.guild.id,))
channel_id = await cursor.fetchone()
channel = channel_id[0]
final = self.client.get_channel(channel)
await final.send("Welcomes activated!")
else:
return``` what do i remove from here .. when someone joins it says welcomes activated?
I'mma just go away before I lose myself yet again
Take care hunter
U 2
if data is None:
return
else:
if data is not None:
this logic is~
can u answer my question if possible'
wtf
pep8 had a stroke after reading this
smarty
a cursor.fetchone() would not return None at any cost normally, am i right?
it does
if there is none
it give me error :(
it will, if the record is inexistent
ah, that makes sense fetchone() returns None, fetchall() would return an empty dict
@slate swan @keen mural not my code though.
When you use calculator to confirm if 2 + 2 = 4 💀
you guys really bullying sarthak out here😔
anyways ... instead of this crap talk . how can i fix
me who just copy pasted a line of someone else's code for them to figure it out 🚶♂️

should i do discord bot tutorials on youtube
- multiple connections
- SELECT welcome
TEXT, you need not specify the column type - same goes with the INSERT, read the above issue
- INSERT's parameters are not in a tuple
- same goes with that SELECT statement for welcome
TEXT
- Fix the sql query, you don't need to
welcome TEXTinINSERTqueries causeTEXTis just the datatype you only need to define inCREATE TABLE - Fix logic
list*
why does API connection not work when hosted on heroku..? It works fine when running on my IDE
well do you understand dpy deeply and discords api and pythons oop?
I didnt, dont, never will expect that from you
well, first you gotta fix your logic ```py
async def on_member_join(member):
data = # get data from your table to check if that guild has welcome setup
if not data: return
you dont need another if else for that....
get your channel, message and other stuff
send the message
...
does any other discord bot tutorial?
that code is literally not more than 10 lines of code
well remember this, a teacher isnt a teacher without their knowledge!
yes
menudocs and CarberraTutorials
i would argue this but i am going to eat pancakes cya guys
how can a teacher teach without knowledge of the topic theyre trying to teach about?🤔
They can, but very poorly
yeah which isnt a great idea
just the way the students are trying to learn calculus without learning addition first
I find teaching in something you aren't very good at, is imo a very great way to learn
well thats just the student not having the base knowledge of a topic no?
Ain’t it sad that I only understand half of what u said
just like knowledge of dpy and python oops before making tutorials on them
Lol
Let's say someone issues a command like: .lastmessage. When I do this command, the bot gets the last message on a specific channel (defined by me) from the person who did the command. Is this possible?
thats indeed possible abc.Messageable.history is what you're looking for 😄
!d discord.abc.Messageable.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
I think that channel object has a last message property
please read their question again, "last message from a user"
I'm already having a bad day, dont add up to it 😔
thank
Didn't read the last part sorry
it's the same slap over and over
steal....why didnt you hide it tbh
show your code again, use the endpoint i used there
me: 🕵️
too lazy to edit image + i dont use tenor api anyways
ok thanks for the key and example then
i think you ment our key?
HAHAHAHA COMMUNISUM
it's funny cuz russia
so whats wrong with this?
i mean that example is available on tenor site itself ( with requests library though)
🚶♂️ btw tried filament yet?
its all your's 😄
whats that-
what is filament
😚
jishaku, but for lightbulb, do you think ill make an eval command by my own?
!pip lightbulb-ext-filament
lmao, thanks for letting me know lol
still the same issue?
bro
well, as you can see in my screenshot, the endpoint works well, and the image loads too
:thonk: maybe using hikari fixes your issue ||jk||
💀
my pip couldnt package it😔
L
@scarlet aurora Don't link to that package please.
plz may i get the rule number i broke
The api returns the same url on every request so ¯_(ツ)_/¯
Rule 1, code of conduct. That package downloads adult content.
oh alr thanks
use random.choice(results) instead of results[0] to get a random gif
alr ty
send ss
ashley💀
just checks its source i checked it and it uses the same api as pykawaii
anyways ot
nsfw endp?
yup
cool
lol
ask them to use pykawaii
good idea
bro
no
🙂
anyways, whats the best way to store an image attachment you get from an user?
use a sqlite db?
no
yes
use a .txt file😳
💀 db, hm, bytes.
yes...
Upload to discord and save the url in db
i was thinking about just storing ....
yea i was about to say that
but if the user deletes that image its permanently gone
yeah if it gets deleted from the cdn the link wont work
Copy that image and make the bot resend it in a private channel and profit
I dont think discord would be happy about that, they may ban the app (maybe)
🤔 that should work!
actually no, a bot named Eli used to do that
discord right now: 😡
Nah they wont. I used this a lot of times lol
I sometimes hate people who make bots nowadays
verified bot?
i hate myself too
Stopped making bots like 6 months ago
high five
you would maybe only want to do this on_delete, unless you already used the image link somewhere, then editing everywhere you used it isn't a good option
BLOB for sql
that should work in my case
@commands.command()
async def slap (self, ctx, member: discord.Member):
embed = discord.Embed(
colour=0xffffff)
embed.add_field(name='Slap', value=f"{ctx.author.mention} slaps {member.mention}", inline=False)
r = requests.get("https://g.tenor.com/v1/search?q=slap&key=token")
choose = r.json().get("results")
url = random.choice(choose)
embed.set_image(url=url)
await ctx.send(embed=embed)``` Can someone help? I'm getting this error ```discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embed.image.url: Must be 2048 or fewer in length. Scheme "{'id': '24271495', 'title': '', 'content_description': 'penguin penguins gif', 'content_rating': '', 'h1_title': '',
'media': [{'nanomp4': {'duration': 1.4, 'preview': 'https" is not supported. Scheme must be one of ('http', 'https').```
That'd be too much work to do like setting handlers, change urls, etc. and it's also risky. What if someone deleted while the bot isnt online?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'get'```
for the url variable...
wym
OH I GOT IT
heyo! does anyone have any idea why the following snippet raises "Deque mutated during iteration"?
for msg in self.bot.cached_messages:
if "test string" in msg.content:
await ctx.send(msg.content)
its been driving me nuts
mind showing the whole error?
it works, i got it now, thanks a lot
basically
your cached messages are changing while you're looping through them
that's something you don't want
maybe check out channel.history instead
but here's the thing, I tried copy.copy() and it still shows the same error
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") permissions to use this.
Examples
Usage...
I specifically need cached_messages to look through a couple deleted messages
deleted messages? hmm, maybe in the logs? not sure if that even gets stored there, I've never sniped messages
name checks out

I'm trying to debug my message logger lmao
it missed one message for some reason and so I'm looking through the cached ones
anyways, a possible better implementation is to keep track of deleted messages in on_message_delete
just keep a cache of all the deleted messages instead I'd say...
how do u do add_field again
you do it after you create the embed
what you're typing is still inside of the embed constructor
i see, thanks
that's not a constructor. What's that called again?
Embed class... ?
add_field is a method, not a kwarg of embed
hey
oh ok
embed.add_field, or use chaining py embed= discord.Embed() embed.add_field(**kwargs) or ```py
embed = discord.Embed().add_field(**kwargs)
i already got it
thats the constructor of a class
guys can someone help me add so , i wanna make it so that level 5+ can use the daily spin command but anyone who doesnt have level 5+ automatically gets a respond that u need to be level 5 to use this command
Is constructor not what you'd call the init method?
well the init dunder is like the parameters of a function which then you call the function but in this case its a class that gets constructed thats how i see it
its really just naming
that's just basic fetching from a db... not too hard if you understand the basics
if you split your "main goal" up in different questions, sure
atleast a command where u can blacklist user / unblacklist from using the bot
idk if i can do that well
basically only level 5 + can use the commands
are the levels roles, or what?
are you reading a db?
yes level roles
there's a decorator that someone else can link for you. It will only allow people with certain roles to use a command
something like discord.Commands.has_roles
That's a thing in js but in python I guess we just call it constructor or callable...? Not sure though.
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
@full lily i didn't say it earlier but i think the name constructor/creation of a class instance fits because since a function signature is where the def a(): is located i think a class signature would be its init dunder or the actual use of the keyword/creation of the class
for anything you are trying to do with database you would first get the data then perform logic operations to see if that condition is true or not ```py
get_level_of_user = ... # get role data for the user
if not get_level_of_user>4: return
do your stuff```
Method 1:
- Check if user has lvl5+ role using
if, elseand.roles, etc. properties - If yes, do the command, else send error
Method 2:
- Use
has_roledeco - If the user does not have that role, it raises
CheckFailure - Catch that using an error handler and send the error
getting the level depends on your exp point system , some people just save the exp, some save exps along with role, so noone can actually help you with that without knowing
- your table structure
- how to you calculate levels
ok better
my bot keeps getting an error but it closes way to fast so i cant see error what do i do
how do i do a blacklist and unblacklist command
your terminal logs never get cleared normally... what terminal are you using?
how do you run the bot
i figured it out
i run it through python main.py but i was doing it wrong
how do i make my embeds look like this
instead of this
like the color?
yeah
Use these ```py
Embed BG = 0x2F3136 # Gives rounded corners
Discord BG = 0x36393E # Gives pointy corners
tysm it worked
u
Which commands upgrades to discord.py v2?
this is a python server
not a roblox traiding server
just make it a database
pip install git+https://github.com/Rapptz/discord.py
.bm
Where do you put that tho?
I get error
ERROR: Error [WinError 2] The system cannot find the file specified while executing command git clone -q https://github.com/Rapptz/discord.py 'C:\Users\bebro\AppData\Local\Temp\pip-req-build-son4n333' ERROR: Cannot find command 'git' - do you have 'git' installed and in your PATH?
install git
you need to install git
Ok thanks guys
in the color kwarg in the embed constructor
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") for you.
Changed in version 2.0: `Embed.Empty` has been removed in favour of `None`.
oh right of course, thx
.bm
Traceback (most recent call last):
File "c:\Users\bebro\Documents\Bots\Chroma Test Bot\bot.py", line 4, in <module>
from discord_components import *
File "C:\Users\bebro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\__init__.py", line 1, in <module>
from .client import *
File "C:\Users\bebro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\client.py", line 12, in <module>
from .component import Component
File "C:\Users\bebro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord_components\component.py", line 3, in <module>
from discord import PartialEmoji, Emoji, InvalidArgument
ImportError: cannot import name 'InvalidArgument' from 'discord' (C:\Users\bebro\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\__init__.py)```
Why I get this error ?
from discord_components import * I get the error on this line
seems like a discord_component internal error
And how can I fix that?
You can’t use discord.py 2.0 and discord_components. Discord.py 2.0 has components do you can use those
And what about the commands and events that i use variables from discord_components?
Ur gonna have to change a lot
https://github.com/Rapptz/discord.py/tree/master/examples/views has some helpful examples
Ok and how can I use that button ?
Is it command or something?
does anyone here knows how to use lavalink
i have a minor problem. Basically, the duration returns 0 for some reason
embed.add_field(name="Duration", value=lavalink.format_time(player.current.duration), inline=False)
Help my bot isnt working
We don't help with lavalink sorry, as that's in violation of Youtube terms of service (assuming your bot can fetch videos from youtube)
We need more information such as tracebacks, code, what your bot is supposed to do, what it's doing now, etc
i need help in #help-cheese , if anyone wanna volunteer it'd be great
on it
i am adding commands
but i already did the rest
and the bot isnt online
even though i did the online script
Alright, you got any errors?
try TOKEN = os.getenv('TOKEN')
Probably a token issue, yeah
Printing it would be a good way to check if your token is really there or not
Though it should've given you an error anyway if it was an incorrect or None token
there's no reason to use getenv or environ.get for your token ever, you should always be using environ["TOKEN"] since if it's not there you dont want a cryptic error like "NoneType has no attribute 'strip'"
One of the occasions where bracket syntax is handy, yeah
Usually I'd prefer .get() instead of a try/catch with bracket notation
In this case though bracket syntax is fine
robin, can you take a look at #help-cheese ? i need some assistance there
TOKEN = os.getenv("TOKEN")
if TOKEN:
bot.run(TOKEN)
else:
raise ...
oh okay!
I'm not familiar with difflib, sorry
wym
try printing your token to see if it's there using print(TOKEN)
You could've just removed the whole if-else since discord.py raises an error for you with a "bad" token
an AttributeError is not the sort of error you want to get for a missing environment variable, dpy raises that unintentionally by blindly calling strip on the given prefix, even if it's None
judging by the looks of it, i think they didnt hit run button LOL
hi
hi
hi
weirdo
Yea, doesn't make sense for your TOKEN to be missing in any case though
hi
And even if you do get past that part, say with a random string "123", it'll raise an HTTP error probably. Since discord.py makes a request for users/@me
how to check user is bot or no? posso mention when reply
if you have a User or Member object you can use the .bot attribute
i want my token to be private
i.e. user.bot or message.author.bot
thx
do TOKEN = os.getenv('TOKEN')
and then try running the code
thats functionally identical to what they already have, what difference would it make?
what where
actually
try replacing
TOKEN = os.getenv('TOKEN')
bot.run(TOKEN)```
with
```py
bot.run(os.getenv('TOKEN'))```
yeah i know its all the same
ARE YOU HITTING THE RUN BUTTON?
should i?
Anyone able to help or explain this? Here's an example
I'm trying to store information in a file but post it in another.
File: key.py
guild_name = "Some Name"
guild_ids = 956462089935941652
File: main.py
import key
guild_name = key.guild_name #WORKS
guild_ids = key.guild_ids #DOESN'T WORK
self._guild_ids_to_rollout: Set[int] = set(guild_ids) if guild_ids else set()
TypeError: 'int' object is not iterable
It works for STR but not INT and I'm unsure why.
i sthere supposed to be 2 ) on the tight
roght
yeah
ok
try putting 956462089935941652 in quotes maybe
thats why you buy replit hacker plan
What? That has literally no effect on importing it, and changes its type from an int to a string...
int is not iterable the error says
so i thought maybe changing it to str will do
Do you have any idea how to fix it? @vocal plover
keeps your bot online, as long as you pay
is there any fre eway for 24/7 online
there is but not 24/7
you'll just want to change it to [956462089935941652], that way it's a list with the guild id
Thank you, I forgot about that one. Lol
vaguely, not to any useful level
I've used it maybe once
can you checkout if you can help me in #help-cheese
how much is hacker plan
7 $ per month
doany other coding languagses have 24/7 hositng
language is irrelevant for hosting
ok
I need youtube video ideas
look into a vps
ive heard its better and cheaper and that replit is still crappy
is it pc only
its a Virtual Private Server
Why doesnt this work
on top of your file?
which kine
what
line
token is None
what
the env variable TOKEN is literal to None :))
what do you mean
the method is returning None
what do i type where

so your code is ```py
bot.run(os.getenv('TOKEN'))
that means that the program will first run ```py
os.getenv('TOKEN')
``` and then use the value returned from that as an argument in ```py
bot.run()
The issue here is that os.getenv('TOKEN') is returning None or that there isn't a value.
When it goes to pass None to bot.run() it fails because that function expects a string argument.
The solution is to alter how you get your token or to ensure that your environment variables are correctly set before you run your code
see above (sorry i forgot to mention you)
bro
Bot.run needs an argument which should be your token which should be literal to a string
your previous code was fine. the issue is you are not properly setting your environment variables.
i put my token as secret
Hey guys im trying to get the last message of a specific channel of the user that use the command !patrulha. i got this code but just give me the message of last user ... and i want the user who use the command !patrulha:
@client.command(name="patrulha") async def fardasHelp(ctx): channel = client.get_channel(int(971165605141037056)) message = await channel.fetch_message(channel.last) await ctx.send(f'Última patrulha mencionada pelo Guarda {message.author.name} foi:\n```{message.content}```')
@cursive barn
my bad
and if Bot.get_channel returns None it would raise an error and you would use history to get the last message of the channel
but i want the last message of the user that is using the command
You can use TextChannel.last_message but it can return None if the message isnt in cache
then it would be the own message that invoked the command
no it wouldn’t wdym?
he tried to fetch a message with the var
hence it would raise NoneType class has no "fetch_message" attribute blah blah blah
I thought you implied that get_channel would throw an error as well as returning None.
nah😅 😭
i should use commas more
my bot isent working
mine's too
my bot exploded
why are discord markdown and embed fields so ugly on mobile phones 🗿
cause phone🛌
async def buy(self, ctx, item, amount: int):
pass```
Trying to make an economy bot with a buy function, but the problem is I can not figure out a way to make it so that when the user types something like `$buy fortnite battle pass 1` I can't seperate the item from the amount, so in this case `fortnite battle pass` from `1`. Can someone help me with this?
$buy "fortnite battle pass" 1
oh so just quotes?
oh wait that makes sense actually
to differentiate from string to int right?
yep, that ill let the item variable take all the arguments inside the quote
nah, thats just how discord py parsing works
Nothing to do with python data types
"this is a text means" this is a single argument
oh alr that makes sense, thanks sarth 🙂 👍
wait
@slate swan couldn't i also do
async def buy(self, ctx, amount: int, item: str): and take the amount first before the item
yes thats possible too, but then add a *, before the item kwarg
help
you didnt pass the token in bot.run...
you type it in there as a string
how
Go to https://discord.com/developers/applications/{your bot id here}/bot, click reset token, after it got reset, copy and put it in your bot.run()
use envs
Sensitive information such as credentials and API keys should be separate from your codebase so that you can share your code with others while ensuring that they cannot access your services, such as your user database.
Hi, is there a reason the poetry configuration of the bots from this discords repo is pointing to an archive of discord.py instead of a release version? Personally I'd prefer using some regular discord.py = X.X.X" if that's not discouraged or something
which one?
Which one referring to which part? Repos?
https://github.com/python-discord/bot/blob/main/pyproject.toml
https://github.com/python-discord/sir-lancebot/blob/main/pyproject.toml
https://github.com/python-discord/bot-core/blob/main/pyproject.toml
Archive?
See above
Discord.py version?
Idk, whichever poetry picks as latest, so atm probably 1.7.3?
An archive was most likely used because the GitHub repository is still under heavy active development. Using an archive means the @unkempt canyon contributors don't experience any sudden changes
that's... corrrect...
1.7.3 is the latest stable release...
Ah I see
unless you dont mention one, its the latest one on pypi
So besides ease of contribution there's no upside?
help
you still have to load the env
check out examples somewhere on how to work with env files in python
What do you mean there is no upside? Using bleeding edge means sudden changes. The upside is you can pick and choose a "stable" bleeding edge release. You get all the juice with no seeds
where
did you even enter the token in the env?
i mad e asecret
named?
token
it should be TOKEN
ok
I mean, poetry locks in the downloaded dependency anyways, so if I work solo I'd be the source of my own bleeding so to speak
I was just afraid of an upside like "Only these archives work with dependency/python version X", but thanks for clarifying :)
great, now load the damn env
save it ig, try running it, if that doesnt work you would need to use dotenv to load the env first
Oh I see, and yea totally forgot about poetry.lock's
because you print it, instead of bot.run("the token")
congratulations , you are ratelimited, type kill 1 in shell and rerun it
now rerun the repl..
aren't we gonna talk about him using "TOKEN" as the token for the bot to run?
or....
💀 wait wtf
cuz its the secrets name
you're not even getting it from the env file my guy
you're just literally passing the string "TOKEN" lol
whats a stirng
?
you need to learn python basics first for sure
but since you're a beginner, please DON'T learn how to code discord py bots through YT
you can learn python perfectly fine with YT, but DON'T learn frequently change libraries through YT, as most code is outdated or just a bad implementation there
i want to add comamnds to my bot and make the token pruvate
i want discord bot
the fact that you don't know what a string or datatype is says enough
not general coding
well, to make B, you need to learn A
OOP programming
whats that
google will tell you, this is a channel dedicated to discord bots
this is not basic python
thatsa welcome vid
yup, exactly what you need
ask in #python-discussion how to get started with python
I’ve been making my discord bots in repl.it and just recently realized that I probably shouldn’t be using it (for various reasons) can anyone recommend me something new to use? ***Something that I can get on google chrome
I would highly recommend switching to a desktop ide there’s just so much more flexibility and features there that you can’t get out of an online ide. Best ide by far: https://code.visualstudio.com/
I can’t afford a desktop I’m not even old enough to get a job. But thanks anyway :))
You don’t need a desktop… any pc will do. In the case that you really have to use something online try https://vscode.dev/
Aight
How can I add multiple values for one embed field?
Wdym? Like multiple lines for one field?
Like.
information on blank information on blank2
info info
info info
multiple lines of inormation for one field
Yea so multiple lines. Use \n for a new line
can I see how I would format it though?
since it's in quotes you can't just type in \n in the quotes
add_field(name="shit", value="poop\npoop")
that works?
ofc it does
never knew 🤣
I coulda swore I tried before and it literally typed out the \n
!e print("not\npossible")
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | not
002 | possible
until you used \\n
hey sarth u are from India right?
yea~
or if you preceed "" with r : r""
that would be a raw string, yes
also explain why, that might be handy for some
👀 you pulled an all nighter on a discord channel...
i sleep for not more than 2-3hrs a day
😱
,
"type": [
"Electric"
],
How do I access the Electric name?
idk man i think u are an alien atleast not human
data["type"][0]
isnt that basic py lmao
dict.get("type")[0]
r"text here" treats backshlashes as normal characters, it makes for example typing windows path easily r"C:\Users\rudie\Documents\file.dat"
and to get more than one just ["type"][0:number]
I always suggest using path libs for functionality like this
nope
or just use linux so you wont have to use \ , but /
just data["type"] will return the whole list
how would I get for say 3 of them?
that's just the same question as "how to get the first 3 elements of a list"
which is called slicing
[:3]
here comes the code
it said message.author has no attribute 'id'
spoiler alert: you're doing .id on a string
message.author most likely isn't what you think it is
i think i am
what if I dont know how many there could possibly be?
for what usecase.
species
I need full code, this can't be
oh wait ik
you defined user again, somewhere
i have 2 user
hm
you can just get the whole list with data["type"]
species?
from what im guessing its a pokemon related stuff
for some reason it's literally printing the ['Mouse']
here comes the pikachu
and to get just the text?
How did you know 🤣
can u send an example of what u mean? u mean like Pikachu mouse Pokemon?
you are using pokeapi.co arent you
pikachu is a mouse? 😮
you can loop through every element and then just add a , in between, that's most likely what you want, right?
just fetch species and use .join()
", ".join(data["type"])
str.join joins elements of an iterable together with a given string, in this case ,
that and Pokemon showdown are prolly one of the best resources available i think even showdown got their data from pokeapi
!e
shit_list = ["shit", "sh", "it"]
joined_string = ", ".join(shit_list)
print(joined_string)```
@potent spear :white_check_mark: Your eval job has completed with return code 0.
shit, sh, it
Lol
I did species = ", ".join(r['species']), thanks 😄
it's Mouse Pokémon
thats species shape like xerneas is life pokemon
make sure the variable is self explanatory
in this case, other devs don't even know if species is a list, a string , ....
so u need to join by space
!bm
What?
?
Why doesn’t it work
i think it starts with dot
.bm
Oh yeah
O lol
Oops
' '.join(data['species'])
if you want only some basic data https://some-random-api.ml/ is noice too
I'm using this api 🤣
oh hm, thats a basic, but neat api
wow i didn't know that
I love some random api
agreeable, for a small scale usage bot, it provides really a lot of endpoints
i just came to know two of in two days before i worked hard with pokeapi like for evo chain that json was a nightmare
i can relate, i was make a wrapper for the pokeapi.co api but never finished
well imma bookmark this thx sarth an y9su
pleasure
yeah pretty a lot of Pokemon names are like jumbled up so lando-therian lando-incarnate some have info some don't some parts are well confusing ig...
the most difficult part is making dataclasses for them , i can just use setattr but that wont show autocompletes for the user and it would just be a guess game
u mean like giving nearest guesses of pokemon name in case they input one wrong?
nah, for wrong pokemon names i have an error
lemme show an example of how the wrapper worked
lets move to an offtopic channel ig?..
How do I set image size?
I had a command named trade I removed it but it still says the command trade is already an existing command or alias
I don’t have it either in my main file or cogs
you have to use pil to resize image
Ah. anyother way
opencv then
does someone know what ctx.channel.create_webhook return?
the docs do
!d discord.TextChannel.create_webhook
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
Requires [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") permissions.
Changed in version 1.1: Added the `reason` keyword-only parameter.
well, it doesnt return anythings
i need id, token
it return none
strange
yeh
I haven't worked with webhooks, so I can't help with that
wdym, it returns a discord.Webhook
yea and i just knowing it like 5 mins ago, because my logs like only giving the webhooks id
does anyone know why the slash cmnds does not get registered ?
reinvite bot, make new url for inviting with the app command checklisted
is this ok ?
should be "yes"
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
group = app_commands.Group(name="hyb", description="-")
@app_commands.command(name="test1")
async def command(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message("Hello!", ephemeral=True)
@group.command(name="sub")
async def test(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message("Hello!", ephemeral=True)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
print('hybrid')
is this correct ?
i had updates this code yesterday buy still dose not work (slash cmnd is not shown)
btw how to mention a specified textchannel with id?
<#id>
i didnt use app_commands
okie
sarthak is speed
thats not how you create slash groups
Are animated emoji's able to work on a bot or would it just not load on a server if it's not added in as an emoji on that server?
i think you can actually do that
i remember seeing it somewhere
there's a different way, you have to do more stuff like
from app_commands import CommandGroup
group = CommandGroup(..)
@group.command or smth
lemme check
discord.py 2.0a slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
group = app_commands.Group(name="parent", description="...")
# Above, we declare a command Group, in discord terms this is a parent command
# We define it within the class scope (not an instance scope) so we can use it as a decorator.
# This does have namespace caveats but i don't believe they're worth outlining in our needs.
@app_commands.command(name="top-command")
async def my_top_command(self, interaction: discord.Interaction) -> None:
""" /top-command """
await interaction.response.send_message("Hello from top level command!", ephemeral=True)
@group.command(name="sub-command") # we use the declared group to make a command.
async def my_sub_command(self, interaction: discord.Interaction) -> None:
""" /parent sub-command """
await interaction.response.send_message("Hello from the sub command!", ephemeral=True)
it works
I'll just go and annoy the dpy people of why they shit on slash commands instead
btw how to make embed field have like "click me" that href into a link?
[text goes here](link)
note this only works in the description and field values
if you want to make the title a hyperlink, consider using the url kwarg instead
hmmm i think arl tried that
embed = discord.Embed(title=f"[{a['title']}]({a['url']})",description=f"By [{a['author']}]({a['author_url']})")
embed.set_image(url=a["fileurl"])
embed.set_footer(text=f"👍 {a['upvotes']} | 💬 {a['comments_num']} | At {a['created_at']}")
embeds.append(embed)```
i got like
imgur in the embed title
use the url kwarg
Embed(title = "uwu", url="https://uwu.me")```
if on the field?
use the above method
okie
only the title is an exception here
Hi
welcome system?
Well ye I guess but I generally came to say hi
im free, rn, might as well help
Do u think we can finish it
how to make a field value none btw?
either use an invisible character or juse set ** ** or _ _ to the field value
maybe
okie thx
Ok I’m going on my pc
code
@warped mirage can we do it a bit faster, i think ill need sleep soon, so if you might
issue ie?
i need a little assistance with difflib in #help-dumpling, if anyone's familiar with it that'd be great
!rule 7
7. Keep discussions relevant to the channel topic. Each channel's description tells you the topic.
oh okay i guess
ill check if it works
nice
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: OperationalError: no such column: welcome``` first error
i just found out about all the different argument conversions that are possible, pretty cool https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#converters
theres no column as welcome the error pretty mch says that, if your schema does provide the column, might as well want to delete the db file and run the program again
is my code correct?
Yeah it’s really nice
seems kinda cool, never knew you could have custom typehints
there's a lot of errors, lets go step by step
bruh i made the db file and now it doesnt add anything , i probs gotta restart code
they give this example
import typing
@bot.command()
async def ban(ctx, members: Greedy[Member],
delete_days: Optional[int]=0, *,
reason: str):
"""Mass bans members with an optional
delete_days parameter"""
for member in members:
await member.ban(delete_message_days=delete_days, reason=reason)
``` which is crazy
`$ban @Member @Member2 spam bot
$ban @Member @Member2 7 spam bot
$ban @Member spam`
pfffttt, you should have basic knowledgeabout sqlite, not the code's fault
might as well just oversee it, considering they dont have good examples except on github, but that sure is some hellish logic
Ok I finally fixed it Gg
And the leave text and welcome text also have been created
lol its a nightmarish thing to imagine doing by hand
good, now try running the code again, and the next error
Ok
I mean....even an average person wont think about that
also so happy copying formatted text does the right thing in android now
Ignoring exception in command set_msg:
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\Dom\Desktop\beta test\cogs\welcome.py", line 71, in set_msg
await cursor.execute("SELECT welcome FROM wm where guild_id = ?", ctx.guild.id)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 37, in execute
await self._execute(self._cursor.execute, sql, parameters)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\cursor.py", line 31, in _execute
return await self._conn._execute(fn, *args, **kwargs)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 129, in _execute
return await future
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\aiosqlite\core.py", line 102, in run
result = function()
ValueError: parameters are of unsupported type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1329, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 995, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ValueError: parameters are of unsupported type```
yo, i was just wondering that does embed properties require message intents too?
make it a tuple
looks like you are giving sqlite some value it doesnt know how to store? maybe it needa to be in a tuple?
makes a tuple without a trailing comma
why would it...?
"messages" and "embedded" messages are termed different right?
or just try it out, but no one's that free unfortunately
thats my question ....
it wont be able to read the embed ofc
yes you can even have embeds in a message
@slate swan wdym by a tuple . aint it ,
average discord rules
oh but wait a message is a data class so might as well have restriction on embeds
hm, that makes sense
see line 71
Yes
!e print(type((1,2)))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'tuple'>
!resources :))
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
'tuh-pul'
or 'two-pul'
Oh my thing ain’t closed ?
1 is correct
tiewpull
Tuple
thats kinda mean isnt it
whatever
yeah ash stop being mean to me or ban
ill savour a ban instead


