#discord-bots
1 messages Β· Page 793 of 1
Yes, but the warning didn't go away
show current code
and the error that it prints?
Everything that outputs
bot = commands.Bot(stuff_you_have_already , sync_permissions=True)
how long ago did you install disnake?
hey , if i use prefix and then type some words separated with space, on using on_command_error i was only able to get the first arg , So
if i use > hi hello ,so it possible to get the whole thing , hi hello
I do not remember exactly, I think a month and a half
update it.
pip install -U disnake
you want to take multiple words in a single argument for a command>
updated
now rerun it
Together with that - bot = commands.Bot(stuff_you_have_already , sync_permissions=True) ?
yep
no i mean , its not for command, like it was for a tts purpose so i want to make it like after prefix the whole sentence i need to get , so...
any code you have currently?
ill suggest you to ask about it in the disnake server
since it comes from library internals
i have made code for tts command, not for error
should i sent?
yea , and
are you using on_message to construct that command?
nop
using commands.command
great. show the current code
ok
cool
@commands.command('tts')
async def tts(self,ctx,*,message):
is_added= check_guild(ctx)
if not is_added:
value = {f"{ctx.guild.id}": "en"}
with open("langs.json", "r+") as file:
data = json.load(file)
data.update(value)
file.seek(0)
json.dump(data, file)
try:
language = json_lang(ctx)
myobj = gTTS(text=message, lang=language,tld='com.au', slow=False)
myobj.save(r"moosik/message.mp3")
try:
await ctx.author.voice.channel.connect()
except:
pass
if ctx.author.voice is None:
return await ctx.send('Pls join a voice channel')
guild = ctx.guild
voice_client: discord.VoiceClient = discord.utils.get(self.bot.voice_clients, guild=guild)
audio_source = discord.FFmpegPCMAudio(r'moosik/message.mp3')
if not voice_client.is_playing():
voice_client.play(audio_source, after=None)
else:
await ctx.reply('Command not done')
except Exception as e:
await ctx.send(e)
!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.
and what error do you want to deal with?
since you already use try/except there
i am not trying to deal with error, if i use > hi how r you i want to make the tts command run
i was only ablt to get hi out of it , so
use * before the parameter to pass every argument after that into one parameter
thats weird since you already have * before message kwarg
like this?
yea
but it gave an error b4, lemme try again
oh i get it, shouldnt you use >tts hi how r you?
if you want it to work as > hi how r you , you'll need to go for on_message listener
means?
will it work with this?
oh tat
i completely forgot abt it
then i will use tat method
using * here gives error anyways
webhook = await ctx.channel.create_webhook(name="ubBot",avatar="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwZm9vZCUyMHN0b3JlfGVufDB8fDB8fA%3D%3D&w=1000&q=80")```
is it correct way to use?
how can i not let the user use the command twice in a row till current is timeout or completed
Can you help?discord.ext.commands.errors.ExtensionNotFound: Extension 'Cogs.Code' could not be loaded.
There is a bot that is salvaged and they shared the code to the public and I want to start it myself and I got the zip file
And it gives this error
discord.py is no longer updated and doesn't support slash commands.
ok
does pycord or nextcord work
help me pls
how to close this when user uses the command again
why dont you just use a cooldown?
if he used cooldown
the cooldown will be on all the members
not for the command user
Bad indents though
async def on_reaction_add(message,user):
await message.delete()```
Hey, I want that my bot deletes messages when there is a reaction on it. It doesnt work with my code. I know this is very basic but I'm new and i couldn't find a answer on stckoverflow or on reddit. So thank you
its a reaction_add event, so the parameters are reaction and user
you can do reaction.message.delete()
!d discord.Reaction.message
Message this reaction is for.
if I use reaction and user as parameters, the message. is underlined and i can't run the code either
it works thanks to you both
I believe there are error handlers about it, UserMissingPermissions something...
let me search it on my bot
so wait, you want to check whether the bot has permissions or the user using that commend have permissions?
so it was BotMissingPermissions, but it didn't worked for me when I used it
@cedar smelt
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=botmissingpermission#discord.ext.commands.BotMissingPermissions
this one was I saw last time
Which one should I use nextcord or disnake to easily add new features to my bot ?
import disnake
from disnake.ext import commands
from disnake import Embed
import json
class ASE(commands.Cog):
"""Ages and Splendor Expanded"""
def __init__(self, bot):
self.bot = bot
@commands.group(case_insensitive=True)
async def ase(self, ctx):
"""Returns the ASE steam page"""
if ctx.invoked_subcommand is None:
ase_embed = Embed(title='Ages and Splendor Expanded',
url='https://steamcommunity.com/sharedfiles/filedetails/?id=2172666098',
description='I Has Ages!',
colour=0xd5000,
author='Made by Melvasul',
image='https://steamuserimages-a.akamaihd.net/ugc/1455177151331418092/0F4DB958BCA9F63CBC5B03EFCFCDBBE88093CEF5/?imw=268&imh=268&ima=fit&impolicy=Letterbox&imcolor=%23000000&letterbox=true')
await ctx.send(embeds=ase_embed)
is there anything wrong here?
I'll suggest Disnake , it's completely your choice though
Go thru their docs and see whats better for you
OK thx
Hy guys how i can means my personal account can join a discord server using python??
Where should i look to solve this problem
!rule 5 , automating user account violates tos
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
it'll get you banned from discord
π
I didn't know that
Means that something is not possible with discord ??? Api??
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'Colour' has no attribute 'pink'```
?????
We've cannot help with this
Leave
Send the code
Ok thx for replying
@bot.command()
async def cba (ctx):
embed=discord.Embed(title="2. trolling, baiting & harassment", description="behaviors to intentionally start conflict or elicit negative reactions is considered trolling. \nthis includes but is not limited to sending abusive direct messages (DMs) to other users or players, purposely trying to bait a user into an argument, name calling, and actively trying to upset or cause arguments.", colour= discord.Colour.pink())
await ctx.send(embed=embed)```
lmao cba
i did random letters :D
oh, you did, cba is cant be arsed, uk slang xD
yk how you come accross some repos and thier commit messages are like "fuck this im done" or "test" or just "asf"
i thought thats what you did xD
oh
lmao
Fuck
I don't think it has a pink attribute
!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.9)").
There is an alias for this called Color...
u can use any hex color
Is there a new library similar to discord.py?
this is how i do
Well there are forks of discord.py now
I would recommend disnake
https://github.com/nestcord/nestcord/ what do you guys think
interesting
It pings role like this... how do I fix it?
await message.channel.send(f"Hey @half iron! Make sure to check this server out!")
Help?
role or member
role
"The best API wrapper for discord you will ever need." kek right
@modern fiberformat is wrong, <@&id_of_role_here>
@cedar smeltcan u show ur parameters?
try msg = await ctx.response.send_message()
oh wait u using disnake or?
cause that is disnake i gave ^^
π
well it dosnt have that attributes
Show yr code
Seems like msg.author is None
await ctx.response.send_message wil return None
!d disnake.Interaction.original_message
await original_message()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the original interaction response message associated with the interaction.
Here is a table with response types and their associated original message...
slashcommands uses interaction not ctx like normal messages
"This function is a coroutine."
When I get home from school I think I'm going to work on creating a welcome card feature
@cedar smelthere,
so instead of response.send_message() use the followup.send caue it returns a msg object
Sure
or that, both will get u a messageobject
that will use a webhook (for ur info)
just fetch it like u had
np
@cedar smeltbut u also have this what i see
aka ctx.message
so seems like no need of fetching orginal message
what is .flatten() in this line: ** await ctx.channel.history(limit=num).flatten()**
!d discord.AsyncIterator.flatten
await flatten()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Flattens the async iterator into a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") with all the elements.
Basically, it will fetch all of the messages up to that limit and put it in a list
join my serverπ
Can somebody recommend database for storing XP (gaining xp by chatting)
is just using JSON okay?
aiosqlite
!warn 933338635720351814 don't advertise or self-promote on our server as per our #rules
:incoming_envelope: :ok_hand: applied warning to @slate swan.
no you should not, it seems like a good idea but json is meant for configuration purpose and not databases
Use some local db like aiosqlite instead
or if you want to keep it like json, use mongodb
!pip motor
!pip aiosqlite
Thanks! Just asking, what are the downsides of using JSON as a database?
- It's not a database
- Frequently reading and writing can corrupt it
- Cant handle large size data
- Used by Hunter
Thanks again
- He caches stuff too
Nice
classified
So is the answer (:
We can't help if we don't see the code...
Are you seriously paranoid someone is going to steal it?
Or is it something to breaks tos?
I'm leaning towards the latter
that error is self explained
no need for code but intressting he scared of showing it, but answer is ||was never awaited||
yh cause its extremely creative
Nobody is going to steal your code
i know i already solved it
am not sure - but why not use specific errorhandlers for specific commands?
@commands.command(aliases=["b"])
@commands.has_permissions(ban_members=True)
async def ban(self, ctx, user:discord.User):
...
await ctx.guild.ban(user, reason=reason)
@ban.error
async def ban_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(f"{ctx.author.mention} *You Missing Permissions.*")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"{ctx.author.mention} *You didnt mention {error.param}*")
``` kinda like this
@cedar smelti just know error.param dont know how to grab what command it was but that is an example of a command specific error
okay the missing permissions one why
@cold sonnetjust example
ah then u better use global π (thanks for letting us know when u find the answers of ur own questions)
damn 100 slashcommands....
is that max allowed or ?
@commands.command('role')
@commands.has_permissions(kick_members=True) #permissions
async def role(ctx, user : discord.Member, *, role : discord.Role):
if role.position > ctx.author.top_role.position: #if the role is above users top role it sends error
return await ctx.send('**:x: | That role is above your top role!**')
if role in user.roles:
await user.remove_roles(role) #removes the role if user already has
await ctx.send(f"Removed {role} from {user.mention}")
else:
await user.add_roles(role) #adds role if not already has it
await ctx.send(f"Added {role} to {user.mention}")
@commands.command('role')
@commands.has_permissions(kick_members=True) #permissions
async def role(ctx, user : discord.Member, *, role : discord.Role):
if role.position > ctx.author.top_role.position: #if the role is above users top role it sends error
return await ctx.send('**:x: | That role is above your top role!**')
if role in user.roles:
await user.remove_roles(role) #removes the role if user already has
await ctx.send(f"Removed {role} from {user.mention}")
else:
await user.add_roles(role) #adds role if not already has it
await ctx.send(f"Added {role} to {user.mention}")```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: role_error() takes 2 positional arguments but 3 were given and im getting this error, its in a cog and everything else in the cog works
oops i sent the code wrong
u forgot self
@role.error
async def role_error(ctx, error):
if isinstance(error, MissingPermissions):
await ctx.send('**:x: | You do not have permission to use this command!**')```
wdym i forgot self, idk what that means
if cog == class, u need self
as first parameter
def test(self, "just a string"):
where would i put that
What could be disadvantages of using rasp pi rahter than a vps to host a discord bot (8gb to be exact)
nothing?
idk what I should do, my bot isnt working anymore
like compare to vps
replit ?
yes
uptime or memory, but your with 8GB is fine
kill container and restart
ok thanks
type kill 1 in shell
the command isnt even working at all
and its not giving an error
@pallid mangodid u put self on the command too
1 gb is not enough anymore for meso I am planning to either upgrade vps plan or just use rasp pi
but im not sure abou uptime
π
@commands.command(pass_context=True, help = 'Delete messages!')
@commands.has_permissions(kick_members=True)
async def purge(ctx, limit: int):
await ctx.channel.purge(limit=limit)
await ctx.send(f"{ctx.author.mention} has cleared `{limit}` messages!", delete_after=5)
@purge.error
async def clear_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send('**:x: | You do not have permission to use this command!**')
and now im getting the same error
self...
but do i put self here too
i told u to put self on all ur commands if they are in a cog
oh, i didnt know because it was a purge command
it dosnt matter what function it is
@pallid mangoif u learned how to make a basic class in python you would know this π
i just watched randoms on youtube
self, is instance of a class so u can reach methods n attributes in a class
this me when youtube
i learn best by fixing mistakes and customizing commands
well u learn best with knowing basic python π
Knowing how subclassing works will help you learn better then
and then start do little more advanced python
Its not even that much of reading to learn the basics of python
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
@pallid mangotake ur time n read throu like those https://python.swaroopch.com/basics.html easy written stuff
but if u still like watching youtube, theres plenty of PYTHON learning videos - not just some guy with outdated discord.py showing little codes without explaining much
that will just make u copy pasta n dont know much
Hey @earnest ingot!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Wait
Are you sure, that I need to specially extract one choice for that?
you can remove import random
and keep the other but then u have to change one part
{random.choice(responses)} to choice(responses)
choice(status)
you using both, probally copy pasta n no clue π
import random
random.choice()
# OR
from random import choice
choice()
i would recommend use last cause that saves u from import unneccesary functions you dont need from random lib
Ok, I'll try
@earnest ingotbut wat was yor error?
RuntimeError: Event loop is closed
Didn't help
But it worked before
what things i should master in discord py to build discord bots
asyncio, functions, some classes, variables and decorators
you need to know some stuff about these to build a discord bot
LOLLLL
what kind of stuff
Yeah Ik
β¦
Iβ¦.
Idk actually, maybe the above comment?
Okay, asyncio may be
But because of one error I'm in JavaScript, so that's why I am on this server
no what discord py library components
@earnest ingotwell i tried help u with the most fundamental import of python modules, but that was too hard π
yeah its my fault, not yours.
and language barrier π
Wdym
import random
random.choice()
# OR
from random import choice
choice()
you use both of those instead of 1.
import random
from random import choice
await ctx.send(f'Question: {question}\nAnswer: {random.choice(responses)}')
await client.change_presence(activity=discord.Game(choice(status)))
Wrong code I sent to you, but now worked
well do u understand what i even mean?
Ye, that when I type one addon twice, Python says: "Get the f||or||k out"
ok, good luck with your coding π
I wanna code a welcome cog that sends something like this when someone joins the server, any idea on how can I code it? I guess I'll need extra modules/packages and some other stuff
Thanks in advance
ty π
does await disnake.VoiceClient.play(source) use await asyncio.sleep()? and if not how do i check when the bot is done playing the source?
!d discord.VoiceClient.is_playing
is_playing()```
Indicates if weβre currently playing audio.
Anyone know what's rate limiter for changing Voice channel name?
1 after every 15 minutes?
it is dynamic
So it means, changing the name in 5 minute intervals is okay?
Sure
Why does guild.approximate_presence_count return None?
U got presence intent?
Ah u mean Invite.approx presence count?
!d discord.Invite.approximate_presence_count
The approximate number of members currently active in the guild. This includes idle, dnd, online, and invisible members. Offline members are excluded.
What
!d disnake.Guild.approximate_member_count
The approximate number of members in the guild. Only available for manually fetched guilds.
New in version 2.3.
!d tracemalloc
New in version 3.4.
Source code: Lib/tracemalloc.py
The tracemalloc module is a debug tool to trace memory blocks allocated by Python. It provides the following information...
does anyone else have to do py import tracemalloc tramalloc.start() at the beginning of their code?
idk, without it my program just gives me some error that tells me to enable traceback in tracemalloc
To see the full traceback
you arent awaiting coros
oh alr
Happens when something isnt awaited
i am
You're not
i await everything
That error happens all the time. You're forgetting to await something
^
no i missed to await smth before, fixed it tho
when you make an API call, you have to await the line right?
like, fork?
no to make request
disnake, usually fetching members and stuff
show tb
thar error is raised whenever you don't await a coroutine
alr
Hello Iβm making discord bot that scrapes tiktok api for follows on the account I am not sure the best way to scrape tiktok anyone know how
By doing the tracemalloc.start() you ain't fixing the issue but just suppressing the error.
oh
well that ain't good
!e
import asyncio
async def coro():
print("lol")
async def function():
coro()
asyncio.run(function())
Does tiktok allow it?
@slate swan :white_check_mark: Your eval job has completed with return code 0.
001 | <string>:6: RuntimeWarning: coroutine 'coro' was never awaited
002 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
lol
Tiktok allows scrapping as long as itβs not malicious
is it malicious?
You don't need to scrape it. It has an open api
No itβs just scrapping follows that the account has
which account?
most social medias have rest apis
Can you give link
Google it
A command that does !follows @user
hmmm
alr kinda sussy baka but i'll allow it
Yes but Iβm gonna use web api as I heard itβs better
Well tiktok's banned in my country so I have no idea about its API
should be everywhere
Itβs not sus itβs just a fun command to check follows an account has
alr
idk the tiktok api, don't use tiktok but stack should help
anyway gtg cya
Kk thx
Ty
yw
@slate swan I think unofficial tiktok package will work better tbh
why so?
They made package for things I want to do so it will work better
I was gonna use selium but I donβt think it would work well
just make a wrapper for the api

like me with the twitter apiπ
O
Iβm not good with wrappers
So Iβll just use ones available to me
lol
Actually I got better idea
Iβll use this websites api: https://tokcount.com/?user=gtm

@slate swan low-key smart bc less work
Bc website scrapes data for me
ig so
how do i get the last 10 members who sent a message in a channel( also i havent used discord.py in a while so be kind ;-;)
Iterate through channel* history and append 10 members into a list
using get channel history?
Good question, and theres not an easy method to do it as far as I am aware. This method may take a while;
How to:
You will need an instance of discord.TextChannel - I will call it channel here
-> Youβre going to want to iterate through channel.history (or use the .flatten() method which I will demonstrate here.
-> You will need to iterate through a large amount of messages in case a couple people have been texting for a while - ill use 1000 messages; bearing in mind it will only take as long as it takes to find the 10 members, and if there are only 3 members who have sent messages it will take a long time and then return nothing
messages = await channel.history(limit=1000).flatten() # this holds a list of the last 1000 messages
members = []
for msg in messages:
if msg.author not in members:
members.append(msg.author)
if len(members) == 10: return
``` once it has finished iterating, `members` will contain the members (instance of `discord.Member`)
OH WHAT
caeden with the help tho
Sweaty answer
omg tysm like damn π
nah professional
ong
& sweaty
love caeden hes the goat
im gonna modify some of the code but thanks so much @manic wing
how can i assign the display roles above everyone permission to a role
how do i fetch the message link of a message
np
ask all your questions now, ill be banned soon probably
why though
π
1) wdym?
2) message.jump_url where message is an instance of discord.Message
bro.
this only returns 1 when there are 5 people
roles can be displayed above everyone like how Owners in this discord is above Admins and everyting below
if u go to roles settings in display
how do i assign it to arole
hm, odd
that 1 is me
because in your code it says is message.author not in members append it
did it stop early?
Did you use it on correct channel?
?
yep
i dont think it did
ill try
although i did reduce the message get size to 100
but that still shouldnt have affected anything
wait do i need some o auth scope?
nope, just message intents
how would i go about turning 120000 seconds into like days, hours, minutes, seconds
that explains it
timedelta
it still doesnt work ( as in it still brings up 1 when there are multiple people in the chat )
try printing msg
print is a useful debugger
you can figure out where shit goes wrong
doing it
dude took it seriously π’
not timedelta lol, you just /60, /60, /24

hmmm
messages = await ctx.channel.history(limit=100).flatten()
message_authors = list(dict.fromkeys([message.author.name for message in messages]))
authors = message_authors[:10] # first 10 authors``` This worked for me @blazing beacon
thank you!
@commands.command()
async def member_count(self, ctx):
await ctx.send(list(dict.fromkeys([message.author.name for message in await ctx.channel.history(limit=100).flatten()]))[:10])
``` little bit better
what is that indentation
@commands.command()
async def member_count(self, ctx):
await ctx.send(embed=disnake.Embed(title='Last 10 members', description='\n'.join(list(dict.fromkeys([message.author.name for message in
await ctx.channel.history(limit=100).flatten()])))[:10], colour=disnake.Colour.green()))
man's trying to fit a novel on one line
then he should put await ctx.message.channel.history
guys what is that?
Gateaway connection error ig
what can i do about it?
It happens every time you run it?
only when the loop calls this line
So I'm getting this errorpy Ignoring exception in on_message Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 487, in on_message if message.author.has_any_role(data[3]) or message.author.has_guild_permissions(self.bot.config.moderator_permissions): AttributeError: 'Member' object has no attribute 'has_any_role'and I'm not too sure why, ik has_any_role exists bc I found it in the docs so maybe it's something wrong with what I'm providing it? I'm giving data[3]an array of roles from my db
Member object doesn't have has_any_role
Are you trying to check, if a user has a certain role?
obviously
He could try if role in member.roles
yeah, checking if a user/member has a role from my array of roles, I can't do command.has_any_role or command.has_guild_permissions bc this isn't a command, it's a on_message event which also handles other messages

what is that indentation
yeah its discord
All my bots look like it
say what now
yeah it's discord
lol
Does your array of roles, consist of role names or ids
ID's
hold up'
Try this ```py
if len(set(roles) & set([role.id for role in member.roles])) > 0: print('Your role is in list')
tweaked it slightly to work with my code and it printed Your role is in list py if len(set(data[3]) & set([role.id for role in message.author.roles])) > 0: print('Your role is in list')
sheesh
so should I use this py if len(set(data[3]) & set([role.id for role in message.author.roles])) > 0: print('Your role is in list') instead of thispy if message.author.has_any_role(data[3]) or message.author.has_guild_permissions(self.bot.config.moderator_permissions):also sorry about the pings, I keep forgetting to turn them off
Does it work?
If it does, then you should use it, because the other method didn't
don't use &, use and
it's bad practice
look here
#set([role.id for role in message.author.roles]))
set(role.id for role in message.author.roles)
You should be able to throw all of that into a set without the list
little things
oh im not sure I didn't read up
I was reading this piece of code :
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="uwu ")
class MyHelp(commands.HelpCommand):
async def send_bot_help(self, mapping):
embed = discord.Embed(title="Help")
for cog, commands in mapping.items():
command_signatures = [self.get_command_signature(c) for c in commands]
if command_signatures:
cog_name = getattr(cog, "qualified_name", "No Category")
embed.add_field(name=cog_name, value="\n".join(command_signatures), inline=False)
channel = self.get_destination()
await channel.send(embed=embed)
bot.help_command = MyHelp()
I don't understand what a command signature is can someone help?
I looked it up in the discord.py documentation it says:
Returns a POSIX-like signature useful for help command output.
what the hell is this??
How do i make a mute command
idk
hi
Create role which can't type/speak and then create function which adds the role to a person
i tried running my python project
and it just plain black
then it closes
help
Do you have VScode?
ye
Ok
Open the project in VScode
i did
and when it is go to your main python file and hit f5
it aint running
This is not the appropriate channel to ask such questions, thanks
i think there is something wrong with my pc or some
DM me
Which api wrapper you're using?
You can ask in #python-discussion or claim a help channel #βο½how-to-get-help
yeah it seems to be working, the bots responding to me again at least which it wasn't doing before when it was erroring, if I tweaked it to bepy if [len(set(data[3]) & set([role.id for role in message.author.roles])) > 0] or message.author.has_guild_permissions(self.bot.config.moderator_permissions):do you think it would still work? i'm not quite sure how to combine these two if statements correctly
I'd change that first part to
if set(data[3]).intersection(role.id for role in message.author.roles)
just a bit more legible imo, other way around works too
Is making a token logger aloud here? like where you have it made and it works and you come here saying its not working and wait for someone to respond?
token logger by?
login a discord bots token?
No
then what?
Like a token stealer
nope
if not then i got to report someone
against tos to steal tokens
^^
Welp now where do i report someone in this discord
Visit their website
Also, this isnt the right channel to discuss about it
Yeah it should
will it though?
[len(set(data[3]) & set([role.id for role in message.author.roles])) > 0]
will be either [True] or [False] because they wrapped it in a list
both of which equate to True when cast to bool, as the list isn't empty
Bro modified my original code, now it doesn\t work
mine was this```py
if len(set(roles) & set([role.id for role in member.roles])) > 0: print('Your role is in list')
not sure why he put brackets there
from bs4 import BeautifulSoup
url = "https://www.tiktok.com/@gtm"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
follow_wrapper = soup.find(id="app")
follows = follow_wrapper.find(class_ ="tiktok-xeexlu-DivNumber e1awr0pt1")
title = follows.find(class_="followers-count")
``` idk what channel to post this so lol
itsa sayin 0
lol
oh yeah i'm using that rn, the reason i added the [ ] in was so that I could add in a the or message.author.has_guild_permissions(self.bot.config.moderator_permissions bit (which didn't work so i reverted that)
if (len(set(roles) & set([role.id for role in member.roles])) > 0) or (message.author.has_guild_permissions(self.bot.config.moderator_permissions)
Should work
unless the right side is broken
oh okay, i had the weird idea that bc it was thing1 & thing2 I couldn't then make it thing1 & thing2 or thing3 without wrapping the first bit in [ ]
jep
did you mean for the ( to be in front of message.author.has_guild_perms()? bc there's not a closing one on the end to match it
π
okay so next question, can someone remind how to strip list things from around my final result? (ik that probs makes no sense). My code is py await message.author.send(f'Your message had `{bad}` in it, This word is considered a "bad" word on this server so your message was removed.') but the bots sending me @SparseSpace ['b2b'] is considered a "bad" word on this server. and i can't rember how to remove the [' '] from the word, i think i need to format it or strip it right?
can there be multiple bad words in the list? if so: ' '.join(list)
If there's only one for sure, then: list[0]
theoretically there could be multiple but chances are there will only be one, i'll migrate any future errors by using the first one
any1 knows why this doesn't work
#EMBEDS
@client.command()
async def displayembed():
embed = discord.Embed(
title = 'Title',
description = 'This is a description.',
colour = discord.Colour.blue()
)
embed.set_footer(text='This is a footer.')
embed.set_image(url='https://www.google.com/search')
embed.set_thumbnail(url='https://www.google.com/search')
embed.set_author(name='Author Name', icon_url='https://www.google.com/search')
embed.add_field(name='Field Name', value='Field Value', inline=False)
embed.add_field(name='Field Name', value='Field Value', inline=True)
embed.add_field(name='Field Name', value='Field Value', inline=True)
await client.say(embed=embed)
client.say is from a very old version of discord.py
Define ctx in the functions arguments and use ctx.send() instead of client.say
Where do people with these ancient syntexs
Because they copy code from old tutorials
from 2006
Very old tutorials
print "Hello to my tutorial"
I installed a python 2 lib once
I had to redo everything, then gave up on the first file
Damn
so something like this?py await message.author.send(f'Your message had `{bad}` in it, This word is conssidered a "bad" word on this server so your message was removed.'.join(bad))I've never been great at formatting strings
how do i set an option in a slash command as Greedy?

Is it possible to do when a person leaves the server, it was written how long he was there?
@slate swan Yeah, you can calculate time between Member.joined_at() and leaving time
!d disnake.Member.joined_at
An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.
@slate swan
@kindred epoch I believe it's here: https://docs.disnake.dev/en/latest/ext/commands/slash_commands.html#autocompleters
so more like this?py await message.author.send(f'Your message had `{"".join(bad)}` in it, This word is conssidered a "bad" word on this server so your message was removed.'). also I'm now getting this error py Ignoring exception in on_message Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 494, in on_message if (len(set(data[3]) & set([role.id for role in message.author.roles])) > 0) or (message.author.has_guild_permissions(self.bot.config.moderator_permissions)): AttributeError: 'Member' object has no attribute 'has_guild_permissions' so obviously something's not right with my if statement logic, one of the reasons I thought i might need to warp the thing1 & thing2 bit in [ ]
Okay
Uh it's because Discordpy-s Member object, doesn't have 'has_guild_permissions'
oh right, that's a attribute of commands
, is there a member equivalent
okay thanks the help, guess i've gotta wade into the docs again
Dude you can make your code 10x easier lmao
You could use commands.has_any_role(role.ids)
So it will check automatically, if the author has one of those roles
And then you could also add commands.bot_has_guild_permissions(**perms)
@client.command()
async def displayembed(ctx):
embed = discord.Embed(
title = 'Title',
description = 'This is a description.',
colour = discord.Colour.blue()
)
embed.set_footer(text='This is a footer.')
embed.set_image(url='https://www.google.com/search')
embed.set_thumbnail(url='https://www.google.com/search')
embed.set_author(name='Author Name', icon_url='https://www.google.com/search')
embed.add_field(name='Field Name', value='Field Value', inline=False)
embed.add_field(name='Field Name', value='Field Value', inline=True)
embed.add_field(name='Field Name', value='Field Value', inline=True)
await ctx.send(embed=embed)
try it
What's the error
his not written ctx
i could do, if I was using a command. i'm using a on_message event since this is a auto mod thing and the event is also handling some other on message things so even if events can take decorators (i have no idea if they can or not) I couldn't use the decorators anyway without making a whole new on message event for this auto mod
what
so other than me not being able to use the has_guild_permissions like i wanted to, is this the correct way to be using .join() ```py
await message.author.send(f'Your message had {"".join(bad)} in it, This word is conssidered a "bad" word on this server so your message was removed.')
put space between " "
Are you about blank pictures?
There's no url in pictures
If I have a subcommand setup like this, will the check from the parent command (fct) apply to the subcommand (foo)?
@commands.group(invoke_without_command=True)
@commands.is_owner()
async def fct(self, ctx):
...
@fct.command()
async def foo(self, ctx):
...
not sure, try it
Most likely not since you don't invoke the base as well. Best is to test indeed.
alright, I'll setup a custom check with some prints, since being owner of the test server I have all permissions π¬
Just remove your ID from the owner list or string
is_owner() checks for the bot owner not the server owner.
yeah I know about is_owner, wasn't sure if I could remove my ID at all
Yeah just remove it and restart the bot. Not too much trouble.
@cloud dawn how are you not a helper now?
What do you mean?
How? π€
datetime2- datetime1
Like you are always helpful, active, so how have you not been "hired"
Subtract the objects with each other.
Alright it does not. Thanks for the tips!
legit 20700+ messages
Well you have to be nominated, idk how it works really, if they asked i would accept.
We'll see ;)
Haha, that is nice :3
But only the staff can nominate users.
Besides i don't really want to ask for 'helper' and tbf nothing much would change.
ye
eivl has 170k
you have to be picked
yes
you gotta be proficient with the language, be friendly to the community and more stuff ig
No clue, i'm just hanging out here and help some people who got questions.
same
@commands.command()
async def f(self, ctx, *, text: commands.clean_content = None):
""" Press F to pay respect """
hearts = [":heart:", ":yellow_heart:", ":green_heart:", ":blue_heart:", ":purple_heart:"]
reason = f"for **{text}** " if text else ""
await ctx.send(f"**{ctx.author.name}** has paid their respect {reason}{random.choice(hearts)}")```
Error:discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
Did you name a function random?
make sure random is not defined anywhere else?
no im not
Could you show how you defined random?
im not, jst import random and yeah. this code
so far it has worked, for some reason the commands have not worked for 2 days
Can you show us your whole code?
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.
damn I was just about to
this code is about 3000 lines
^
Doesn't matter we got ctrl+f
and I am stalling from doing hw so take as much time as you want
from random import *
class fun(commands.Cog):
def __init__(self,client):
self.client = client
@commands.command()
async def f(self, ctx, *, text: commands.clean_content = None):
""" Press F to pay respect """
hearts = [":heart:", ":yellow_heart:", ":green_heart:", ":blue_heart:", ":purple_heart:"]
reason = f"for **{text}** " if text else ""
await ctx.send(f"**{ctx.author.name}** has paid their respect {reason}{random.choice(hearts)}")
That's the top of the code.
It was not defined anywhere.
ahh
just import random
Well then it's just choice
{choice(hearts)}
oh
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
4
but if you change it to import random
omg ty
With 3k lines changing an import could break a lot
ye ig
Best is to indeed avoid using the *
But for standard libs or if you are really familiar with it it's fine.
!e py import random print(random.choice(1,2,3)) print("vs") from random import * print(choice(1,2,3))
@karmic totem :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | TypeError: Random.choice() takes 2 positional arguments but 4 were given
from random import (
choice as randchoice,
randint
)
If you really want it shorter but do keep it clear what you are doing.
how do i make a guild
!d discord.ext.commands.Bot.create_guild
await create_guild(*, name, region=<VoiceRegion.us_west: 'us-west'>, icon=..., code=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").
Bot accounts in more than 10 guilds are not allowed to create guilds.
discord.ext I think
i don't know what I'm doing wrong but this command just doesn't seem to be working and I don't seem to be getting any errorspy @commands.has_permissions(administrator = True) @commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to said on the server..") async def badwords(self, ctx, *, words: str): data = await self.bot.get_data(ctx.guild.id) print(f"Input: {words}") bad_words = [] bad_words.append(data[28]) for word in words: bad_words.append(word) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) await ctx.send(embed = discord.Embed(description = f"The bad words list has been update to be `{', '.join(data[28])}`.", colour = self.bot.primary_colour))
When you type the command what does it say?
nothing, it just doesn't respond and it also isn't printing me any error's
but it's responding to other commands
When you type it does something pop up on the console from where ur hosting ur bot
nope
Does hikari have a method to see if a user is pinging themselves in a message? Like when I ping @paper snow (me). I tried comparing the event.author.mention to the mention string in the message, but '@paper snow' and '@paper snow' are not the same.
and the command i'm using is ,badwords act2 b2b "act 2" "act 2 b2b" glitch
are your prints printing?
nope π I'm thinking it could be related to this error with one of my on_message events but I'm not sure why it would be, only reason I think it might be related is whenver I've had issues with on_message events in the past it's always locked up my bot but it's not locking up the bot this time, only this one command. the error on the on_message ispy Ignoring exception in on_message Traceback (most recent call last): File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "/home/modmail/cogs/events.py", line 485, in on_message data = await self.bot.get_data(message.guild.id) AttributeError: 'NoneType' object has no attribute 'id'
message.guild is None if the message was sent in direct messages
you want to check for that before accessing its id attribute
would this work or do I have to do isinstance(DMChannel) py if message.channel != DMChannel: data = await self.bot.get_data(message.guild.id)
!d discord.Message.channel
The TextChannel or Thread that the message was sent from. Could be a DMChannel or GroupChannel if itβs a private message.
better to just check if message.guild is None
and no that wouldn't work how you're doing it
okay well that fixes my on_message errors but I'm still not getting a response from this commandpy @commands.has_permissions(administrator = True) @commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to be said on the server.") async def badwords(self, ctx, *, words: str): data = await self.bot.get_data(ctx.guild.id) print(f"Input: {words}") bad_words = [] bad_words.append(data[28]) for word in words: bad_words.append(word) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) await ctx.send(embed = discord.Embed(description = f"The bad words list has been update to be `{', '.join(data[28])}`.", colour = self.bot.primary_colour))which as far as I can tell should be working with this command ,badwords act2 b2b "act 2" "act 2 b2b" glitch
@commands.command()
async def ping(self, ctx: commands.Context):
start_time = time.time()
message = await ctx.send("Loading ping ")
end_time = time.time()
if round(self.angel.latency * 1000) <= 30:
emoji = ""
elif round(self.angel.latency * 1000) >= 31:
emoji = ""
elif round(self.angel.latency * 1000) > 100:
emoji = ""
if round((end_time - start_time) * 1000) <= 300:
emoji2 = ""
elif round((end_time - start_time) * 1000) >= 301:
emoji2 = ""
elif round((end_time - start_time) * 1000) > 1000:
emoji2 = ""
em = discord.Embed(description = f'{emoji} Bot Latency: {round(self.angel.latency * 1000)} ms\n{emoji2} API latency: {round((end_time - start_time) * 1000)} ms', color=discord.Color.from_rgb(black1, black2, black3))
em.set_author(name="Pong")
await message.edit(embed=em)
why if it's over 1000/100 it wont display the red dot?
it looks like it stops at the orange dot
should be red
why isnt this command working?
async def stats(ctx):
NoBotsMemberCount = len([m for m in ctx.guild.members if not m.bot])
BotsMemberCount = len(ctx.guild.members) - len([m for m in ctx.guild.members if not m.bot])
stat_em = discord.Embed(title=f"{ctx.guild}'s Stats:", colour=0x2c1945)
stat_em.add_field(name="Member Count:", value=f"{NoBotsMemberCount} Members", inline=False)
stat_em.add_field(name="Bot Count:", value=f"{BotsMemberCount} Members", inline=False)
stat_em.add_field(name="Channel/Category Count:", value=f"{len(ctx.guild.channels)} Channels", inline=False)
stat_em.add_field(name="Boosts:", value=f"{str(ctx.guild.premium_subscription_count)} Boosts", inline=False)
stat_em.set_footer(text="https://github.com/zoaq1")
await ctx.message.channel.send(f"{ctx.message.author.mention}", embed=stat_em)```
Enable member intents
Also check out pep8
Variables should be named in snake_case
too bad
Why are people so opposed to making semi readable code
fine
probably since its new and their lazy
their
?
Oh the github is empty
if i do an on_message(message): and take that message variable and send the whole thing through a webhook? how can i do that if i even can?
how do i make my mute command ignore the bot
can i do something like this if member ==bot.get_user(bot_id): await ctx.send('cannot mute the bot')
well the pep8 in that code is terrible but yea
just make sure to return the message so the command stops at that
Better to compare id's
if member.id == bot.user.id:
return await ctx.send('Cannot mute the bot')
ok thanks
if someone sends a link in a channel, anyway to extract the link from the message into a string?
just use message.content
Best is to use regex for this
s = message.content
for y in s.split(β β):
if y.startswith(βhttpβ):
print(y)
that should get the job done
thank u
!e ```py
import re
url_regex = re.compile("http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+")
sample_text = "haha check this out https://google.com lol"
if res := re.search(url_regex, sample_text):
print(res.group(0))
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
https://google.com
that works better ^
This is really limited also would break very easily.
thanks it works
@cloud dawn your right, it was just a way to get it done
have any solution to this @cloud dawn
Don't think webhooks can send objects.
They send json like data iirc
i should learn re
π¦ off to filtering and extracting data i go
That's my regex for url's :3
lol
mine looks esoteric
!e
print("stringhttps://www.youtube.com/".split('https', 1)[1].split('.com/', 1))
@slate swan :white_check_mark: Your eval job has completed with return code 0.
['://www.youtube', '']

thank u dude it works
panda is probably the god of regex
Where did the https go
no need for the protocolπ
idk if all urls work since discord has some weird ones but this should get a lot.
it works
I almost found the best regex ever
where
_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS
that looks so esoteric
holy fucking shit
Mine is shit compared to this lol
lmaoo
pretty interesting website
This regex beats most build-in url checks lmfao
@(https?|ftp)://(-\.)?([^\s/?\.#-]+\.?)+(/[^\s]*)?$@iS
``` this one is pretty clean.
import discord
@discord.Client().event
Does this just detect when the bot is actually logged in to itself, if you know what I mean?
so i recently added the snipe command, and now no other command is working
the snipe command works fine, but the others dont, and no error message either
make it a listener
pardon?
from
@client.event
turn it to
@client.listen()
Can anyone find any error's in this code? I'm not seeing anything wrong here but my bot's not responding to the command and I'm not getting any error's or print outs and it's really confusing mepy @commands.has_permissions(administrator = True) #@commands.guild_only() @commands.command(description = "Sets the bad words that aren't allowed to be said on the server.") async def badwords(self, ctx, *, words: str): data = await self.bot.get_data(ctx.guild.id) print(f"Input: {words}") bad_words = [] bad_words.append(data[28]) for word in words: bad_words.append(word) print(f"Bad Words: {bad_words}") async with self.bot.pool.acquire() as conn: await conn.execute("UPDATE data SET badwords=$1 WHERE guild=$2", [word for word in bad_words], ctx.guild.id,) await ctx.send(embed = discord.Embed(description = f"The bad words list has been update to be `{', '.join(data[28])}`.", colour = self.bot.primary_colour))but the bot is responding fine to other commands
thank you so much, will try to see if it works now
yw
uh oh
Itβs a Bot only method
?
hes using commands tho?
You probably meant to do @bot.listen(). Donβt use client and bot in the same file
thanks
no need for client when Bot is a subclass of the client class
!d discord.ext.commands.Bot
class discord.ext.commands.Bot(command_prefix, help_command=<default-help-command>, description=None, **options)```
Represents a discord bot.
This class is a subclass of [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") and as a result anything that you can do with a [`discord.Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") you can do with this bot.
This class also subclasses [`GroupMixin`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.GroupMixin "discord.ext.commands.GroupMixin") to provide the functionality to manage commands.
This class is a subclass of discord.Client and as a result anything that you can do with a discord.Client you can do with this bot.
the commands extension is there for a reason, use it
if you really don't want to, you need to bot.process_commands(message)
no
!d discord.ext.commands.Bot.process_commands
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.
actually, the commands extension is better
anything to change here or no
no
cuz its still not working
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.
send the url
do i put the link her
yes
no your link
that is my link
its not
nothing else ther
you have to add the code and press the save button
there should be a id at the end of the link
you haven't changed this?
the snipe command works
huh
why are you instantiating two different bots
remove client
change client to bot
no remove the whole client var
and replace all instances of client with bot
which line is it
17
on top?
you mean 18? or am i looking atthe wrong place
yeah 18
yes 18
it's 17 on the haste π
remove it?
yes
and make all the instances to bot
also done
and change line 81 to @bot.listen()
this to bot as well?
remove it or delete
its the same thing?
so i remove it
and i'd highly recommend using the commands extension because you're already using commands.Bot
don't go through the pain of using on_message commands
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
A full traceback could look like:
Traceback (most recent call last):
File "tiny", line 3, in
do_something()
File "tiny", line 2, in do_something
a = 6 / b
ZeroDivisionError: division by zero
The best way to read your traceback is bottom to top.
β’ Identify the exception raised (in this case ZeroDivisionError)
β’ Make note of the line number (in this case 2), and navigate there in your program.
β’ Try to understand why the error occurred (in this case because b is 0).
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
how do i fix this
send the tb
pardon?
send the whole traceback
in terminal?
Traceback (most recent call last):
File "C:\Users*my name\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "c:\Users\my name\riotbot #3.py", line 51, in on_message
msg = sys.argv[1].split(",")
IndexError: list index out of range
sys.argv doesn't have a second item
!e
a = ["lol"]
print(a[1])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | IndexError: list index out of range
you cant index something that doesnt have such an element
how would i fix that
sys.argv```
The list of command line arguments passed to a Python script. `argv[0]` is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the [`-c`](https://docs.python.org/3/using/cmdline.html#cmdoption-c) command line option to the interpreter, `argv[0]` is set to the string `'-c'`. If no script name was passed to the Python interpreter, `argv[0]` is the empty string.
To loop over the standard input, or the list of files given on the command line, see the [`fileinput`](https://docs.python.org/3/library/fileinput.html#module-fileinput "fileinput: Loop over standard input or a list of files.") module.
See also [`sys.orig_argv`](https://docs.python.org/3/library/sys.html#sys.orig_argv "sys.orig_argv").
Note
On Unix, command line arguments are passed by bytes from OS. Python decodes them with filesystem encoding and βsurrogateescapeβ error handler. When you need original bytes, you can get it by `[os.fsencode(arg) for arg in sys.argv]`.
remember that python counts from 0
uhuh
!e
example_list = [1, 2, 3, 4, 5]
print(example_list[0])
@slate swan :white_check_mark: Your eval job has completed with return code 0.
1
i mean what command did you type into terminal
it detects the messages
what command did you use (e.g. python3 main.py) to start the script?
not only that
shows up in terminal
to retrieve command line arguments
how would i make this better then
just why
if you want to get args of a command just print them?
im not sure what you want
then why have it?
sys.argv retrieves arguments when you run it through terminal, for example python3 main.py 1 2 3 would make sys.argv ["1", "2", "3"]
you can't get the user's timezone
yes
wdym
you need to pass arguments while running your script to populate sys.argv
for example python3 main.py 1 2 3
i don't even get why you are using sys.argv here
would i remove it
that line has been removed, anything else?
that whole listener is messed up, cause msg and regexGroups isn't defined
don't know what you want msg and regexGroups to be, so you need to somehow define it
would i delete that entire line?
member is not defined
show traceback
there is none
nothing we can do about it :/
tf?
then where are you getting member is not defined
shows this now
yeah it's defined, but you're not using it anywhere
do i remove that line then?
just showed up
wdym
quick fix ig
for what
the mem
the what?
it was "mem" before
Did discord.py receive an update?
nope

