#discord-bots
1 messages · Page 526 of 1
- Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.
- Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.
- Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.
- Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)
- Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.
using slash commands makes me think it's not a private bot
My bot is on heroku
not slow ¯\_(ツ)_/¯
Ik about that already
But as i said, for a private Bot heroku is good
Google Cloud Services is better imo it doesn't cost much either
You need a cc
yes because its paid
Exactly
Not everyone got one of those
while I was using heroku, I made two heroku accounts so that if one exceeds the 550h/month, I just start the app on the other account
@slate swan after putting it in the requirement file
That's what I'm doing 😎
one more reason to not use heroku?
seems like too much hassle lol
works fine for what i need it to do
Don't blame heroku for his fault
what did he do wrong
The name of the lib isn't discord_slash, check again
!pypi discord_slash
¯\_(ツ)_/¯
do you have any idea what the lib is
¯\_(ツ)_/¯
Check if the user that dm'ed you is a bot or not
U mean make every command not work in dms?
like dont allow commands to be used if you dm the bot
@discord.ext.commands.guild_only()```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command.
This check raises a special exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Add that to all of your commands
or use a bot.check
Or you could also simply make a bot check if you know how to
if u hadnt pointed it out i wouldve probably just removed slash commands lol
How does one make a better help command?
I tried pretty_help but it doesnt seem to be the best/has limited customization.
wow
^
I don't want a static one, cause I am kool 😎
hey guys
im having a bit of a problem
ModuleNotFoundError: No module named 'discord'
does anyone know how to help with this, if so please let me know
i have it installed through pip and stuff but it still says this its confusing and nothing is helping no matter what i try
through pip and pip3?
type python -v
and python3 -v
yes i did it through pip and pip3 do i do that other stuff in place of that?
can you give me like an example?
im a little slow sorry
Most if not all the tutorials I see use pip install but on my Ubuntu machine I had to do pip3 install. No one seems to have the same problem, though it's not really a problem. If I use a virtual environment, though, pip install works fine.
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Hey, can anyone tell me why my author/thumbnail isnt working? Ive been trying to figure out why but i have no idea... Code is below.
title=f"{twitch_username}'s Twitch Stats",
description=f"Username: {twitch_username}\nAccount Creation: {twitch_creation_tidy}\nBan Status: {twitch_ban_stat}",
colour=discord.Colour.green()
)
embed.set_author(name='Utango')
embed.set_thumbnail(url=twitch_pfp)
await ctx.message.channel.send(embed=twitch_stats_embed)```
ah i figured it out... Im dumb
Hey, so I'm trying to make an event function that sends a message to the logs channel when a message is deleted. This is the code I have so far:
import discord
from discord.ext.commands import Bot
import datetime
client = Bot(command_prefix='>')
logs_channel = client.get_channel(896464547588759603)
intent = discord.Intents.default();
intent.members = True;
intent.guilds = True;
@client.event
async def on_ready():
print("Portfolio bot is now running.")
# On delete event filter
@client.event
async def on_message_delete(message):
if not message.author.bot:
embeded = discord.Embed(color = 0xEE8700)
embeded.add_field(name = "Message has been deleted:", value=f"{message.author} has sent the following message which is now deleted:\n'{message.content}'\n\nDate: {datetime.date.today()}\nUser ID: {message.author.id}")
await client.wait_until_ready()
await logs_channel.send(embed = embeded)
client.run("token :)")
And it returns a Attribute Error: 'NoneType' Object has no attribute 'send'
Can someone tell me what I'm doing wrong?
man i cant even import discord
the issue is that its trying to get the channel before the bot is ready which is why it's returning none
try putting logs_channel = client.get_channel(896464547588759603) inside your event
i get the error for no module when i try to run my bot
ModuleNotFoundError: No module named 'discord'
Ahhh thanks so much it works now ! :)
and you did pip install discord.py ?
yes i did
what IDE are you using?
VS
What OS are you using? Because when I tried running discord.py on my mac it wouldn't work
windows
oh
i did both pip install discord.py and discord
and it says it worked and installed
but when i try to run the bot it gives me the error
try this: uninstall both modules, reinstall, restart your ide
weird im still getting the error
you only reinstalled discord.py too right
yes
do you have multiple versions of python installed?
so i need to uninstall 3.10 and install 3.8?
I would yeah, i doubt thats the issue though
I had similar issues before and it was because i had multiple versions of python installed
so it should work with 3.10?
I saw some people are already using, i guess there should be no problems
on the github it had this 🤷♂️
How do I send a message
like an @ message
with only the name of the person who sent it
wdym?
like I have
author = message.author
and if you print it
it is
the name of the person
but I want it like @solid wave
not just Asad
then use message.author.mention
property mention: str```
Returns a string that allows you to mention the given user.
ok thanks
message.author is a discord.User or discord.Member instance
So you can use this
yeah
also one more thing
if someone sends a message
how do I make sure they have the authority
like if they have a certain role to do it
how do I get their roles
i assume you are using on_message event. You need to define commands using command decorator and add checks for that
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
give me an example
which part tells me how to get roles
i am needing some sample code that has my bot interact with a telnet server and processes the responce
here is the ip info and the port
10.0.0.1
port:8080
ok
The rules and guidelines that apply to this community can be found on our rules page. We expect all members of the community to have read and understood these.
1. Follow the Python Discord Code of Conduct.
I just started doing bots with python for discord and I already got a problem.
I took this guys script form youtube and isn't working on my server...
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
async def on_message(message):
username = str(message.author).split("#")[0]
user_message = str(message.content)
channel = str(message.channel.name)
print(f'{username}: {user_message} ({channel})')
if message.author == client.user:
return
if message.channel.name == 'kk':
if user_message.lower() == 'hello':
await message.channel.send(f'Hello {username}!')
return
elif user_message.lower() == 'bye':
await message.channel.send(f'See ya {username}')
return
elif user_message.lower() == '!random':
response = f'random: {random.randrange("Você conhece a piada do pônei? Pô nei eu", "O que o pagodeiro foi fazer na igreja? Cantar pá God", "O que o pato falou para a pata? Vem quá", "Você sabe qual é o rei dos queijos? O reiqueijão")}'
await message.channel.send(response)
return
if user_message.lower() == '!anywhere':
await message.channel.send('This can be used anywhere!')
return
client.run(TOKEN)```
The script is logging on the bot account, but not reading or responding to messages.
What it's wrong?
async def on_message(message):
if await events.is_not_restricted_channel(message):
if message.author == bot.user:
return
else:
print("Processing")
await bot.process_commands(message)```
Process command is not working ?
Can anyone help me in this?
- youtube tutorials for discord.py are all pretty bad (teach bad practices etc)— try to keep away from them if you can
- you need to add the event decorator to your on_message event as well
Thanks!! I really needed this message.
Do you have any font where I can learn about discord.py?
reading the docs is always a good place to start– they have examples
how would I get <t:1633827472:F> to work and whats it called so I can find docs and stuff for it (someone showed me this and I have no clue whats happening but it converts to different timezones)
Thanks, 🙂
they're called timestamps
oh ok
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
np
oh wait
https://discord.com/developers/docs/reference#message-formatting this link for wider context
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
?
logs = await guild.audit_logs(limit=1, target=discord.AuditLogDiff.vanity_url_code).flatten()
type object 'AuditLogDiff' has no attribute 'vanity_url_code'
How would I fix this?
Is there any way to get if a user was mentioned in a string? I'm pretty sure there is I just forgot how. Say I have '@mortal dove', it would know that @mortal dove is an instance of discord.User, from the string. Hope that makes sense? Basically it needs to take in a string or a user, and do something if it is a string and something else if it is a user.
so basically within the same command, you're trying to target either a user or a string?
Yeah
whats the code for your command and what are you trying to do
If it helps, it's for a purge command. You can either do 'bot' (and similar), 'user', 'all', or mention a user
It's kinda a lot one sec
!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.
for user and bot wouldnt it be easier for it just to be categorized under user since they all are under the same object?
I would do this, but I also may want to delete all messages by kyle that ping jeff, and the list is unordered
Or all messages that ping jeff, or all messages by kyle
iterate over it then?
Unordered, so I would be confused over more than one ping
Just to make sure I’m understanding this right. You want to delete any message that has a mention of a specific user?
yeah, so he basically wants it to do that, and have it so that it's optional in which case he can just purge messages like normal
Literally just
Delete Everything from Kyle that includes Jimmy != Deleted Everything from Jimmy that Includes Kyle. There's no difference in the unordered list
yes but
Actually hold on
Im gonna use MS paint to demonstrate my point one sec
@commands.command()
async def purge(self, ctx, user: discord.Member = None, amount: int = int):
if user == None:
if amount == None:
await ctx.message.channel.purge(5)
await ctx.send(f'Purged 5 Messages!')
else:
await ctx.message.channel.purge(amount)
await ctx.send(f'Purged {amount} Messages!')
else:
if amount == None:
async for message in ctx.channel.history(limit = 5):
if message.author == user:
await ctx.message.channel.purge(5)
await ctx.send(f'Purged 5 Messages From User: {user.name}')
else:
async for message in ctx.channel.history(limit = amount):
if message.author == user:
await ctx.message.channel.purge(amount)
await ctx.send(f'Purged {amount} Messages From User: {user.name}')```
lmk if this is what you wanted
and if it works
i havent tested it yet lol
is that what you wanted?
py
logs = await guild.audit_logs(limit=1, target=discord.AuditLogDiff.vanity_url_code).flatten()
type object 'AuditLogDiff' has no attribute 'vanity_url_code'```
How would I fix this?
@commands.command()
async def purge(self, ctx, user: discord.Member = None, amount: int = int):
if user == None:
if amount == None:
await ctx.message.channel.purge(5)
await ctx.send(f'Purged 5 Messages!')
else:
await ctx.message.channel.purge(amount)
await ctx.send(f'Purged {amount} Messages!')
else:
if amount == None:
async for message in ctx.channel.history(limit = 5):
if message.author == user:
await ctx.message.channel.purge(5)
await ctx.send(f'Purged 5 Messages From User: {user.name}')
else:
async for message in ctx.channel.history(limit = amount):
if message.author == user:
await ctx.message.channel.purge(amount)
await ctx.send(f'Purged {amount} Messages From User: {user.name}')```
wait i fixed it a bit @mortal dove
i messed up with the ctx.author
This only solves like 1/2 of the guys problem tho. He said he wanted to purge messages that were by that specific author and that included a specific mention of someone.
isnt that what he meant? purging someone specifics messages?
and that included a specific mention of someone.
oh basically if that persons name was mentioned inside of a message it would get deleted?
yeah
thats not bad
if discord.User.mention in [x.mention for x in discord.Message.mentions]
...
async for message in ctx.channel.history():
if user.mention in message.content:
await message.delete()```
would that work?
what is the dif btw thread remove and delete?
Just use the check argument of the purge method to only purge messages of a specific user
why my bot.process_commands(message) is not working.
There is command written but the command is not getting run
dont put await bot.process_commands(message) in else /elif/if statements
just to make sure, if I have my discord bot in Server A only
and someone that isnt in it will not be able to use it ln the DMS right
guildid=894378876883578890
@bot.command()
async def whois(ctx,*,message:int):
guild = bot.get_guild(guildid)
whoisuser = guild.get_member(message)
await ctx.send(f"**{message}** is **{whoisuser}**")
print(f"**{message}** is **{whoisuser}**")```
how would i make this get_member from all the guilds it's in
Uhm i think theres some author thingy u can use
So you dont need to do the whoisuser stuff
@bot.command()
async def whois(ctx,*,message:int):
username = str(message.author).split('#')[0]
guild = bot.get_guild(guildid)
await ctx.send(f"**{message}** is **{username}**")
print(f"**{message}** is **{username}**") ```
try this not sure would it work tho im new at these too
is it possible to know with which invitation code a member enter? ,':
I mean doing it in code, with the event on_member_join
Is it sending the id’s?
@bot.event
async def on_member_join(member):
# Getting the invites before the user joining
# from our cache for this specific guild
invites_before_join = invites[member.guild.id]
# Getting the invites after the user joining
# so we can compare it with the first one, and
# see which invite uses number increased
invites_after_join = await member.guild.invites()
# Loops for each invite we have for the guild
# the user joined.
for invite in invites_before_join:
# Now, we're using the function we created just
# before to check which invite count is bigger
# than it was before the user joined.
if invite.uses < find_invite_by_code(invites_after_join, invite.code).uses:
# Now that we found which link was used,
# we will print a couple things in our console:
# the name, invite code used the the person
# who created the invite code, or the inviter.
print(f"Member {member.name} Joined")
print(f"Invite Code: {invite.code}")
print(f"Inviter: {invite.inviter}")
# We will now update our cache so it's ready
# for the next user that joins the guild
invites[member.guild.id] = invites_after_join
# We return here since we already found which
# one was used and there is no point in
# looping when we already got what we wanted
return
So you want to know who invited a specific user to your discord server? Don’t worry, this is quite a simple thing to do. By the end of the…
thx
How do I find if a string has a mention in it without using message.mentions?
This is impossible to read
'Guild' object has no attribute 'vanity_url_code'
what would the correct object be
this has me so confused
was on phone cant copy paste properly
I actually wanted to make a command like botdie which can kill the bot and botalive which can bring it back to life idk if it's possible
um yea that's possible
instead of killing the bot you can suspend it, so any other commands won't work
How??
one sec
Oh ok
I don't want to write it in front of each command
for command in client.commands:
command.update(enabled=False)
``` will disable the commands
Oh thanks
is it possible to record microphone and play it at the same time on a discord bot?
why are you spoonfeeding
I have a functioning bot but how can I make it when it gets pinged it says the help command
check the mentions in the messages
if your bot is in that list, then send the help command
check if the bot is mentioned , and use
!d discord.ext.commands.Bot.get_command
get_command(name)```
Get a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get the subcommand `bar` of the group command `foo`. If a subcommand is not found then `None` is returned just as usual.
you can invoke the help command then..
they asked whats the use of it
Idrk
So I showed what it does
I have seen impersonation commands that use webhooks though
Like making it look like someone is saying something using a webhook message
It deletes the webhook
Cool
!d discord.WebhookMessage.delete
await delete(*, delay=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the message.
for that
m is None if I do
m = await webhook.send(...)
Sad
No I don't want help, just saying something I noticed
ehm okay
it takes ids and tells you a username
And your trying to get the server name list?
bot?
Oh i can give you that
okay
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
@slate swan
ty
How would I create buttons for a user to interact with?
2.0v of discord.py needed
Thank you. Also, what's the latest version of discord.py?
Would it be 2.0?
it is 1.7.3, but there is unreleased 2.0.0
So would having 1.7.3 be best?
Since you're saying that 2.0 is unreleased
yes it is unreleased because some features not ready, but there is all features of 1.7.3 and views (buttons, dropdowns), ephemeral messages, banners, guild avatars and much more ready
because that i am using it
buttons are impossible in 1.7.3
Will 2.0 be releasing anytime soon?
I don't know
@burnt wharf there is this task board https://github.com/Rapptz/discord.py/projects/3
but already about month there is nothing changed
it like, stopped
xD
how can I add proxies on my python file...
like...I have a bot and it frequently gets blocked by discord api...How can I use a random proxy whenever I start the bot??
Why is your bot getting blocked?
u mean api blocked?
how do I add a debounce for my discord bot?
a debounce would prevent the user from spamming & overloading the bot
a cooldown?
yeah basically
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command")
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.BucketType "discord.ext.commands.BucketType").
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CommandOnCooldown "discord.ext.commands.CommandOnCooldown") is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") and the local error handler.
A command can only have a single cooldown.
^
oh
thanks
development on dpy has stopped because the maintainer wanted to move on and nobody he trusted stepped up to take over
How can I send a message to all server where my bot is in?
for g in bot.guilds: send message
spam is not a good thing...
!d discord.Client.guilds , gets you all guilds
choose a channel to send message in , and use channel.send
property guilds: List[discord.guild.Guild]```
The guilds that the connected client is a member of.
why would you want to do that though?
I want to tell the server the update of my bot
lol ok
I know spam is bad but can you give me any sample codes?
Plz
for g in bot.guilds:
await g.system_channel.send('HeY, ThErE iS a NeW uPdAtE oF mE')```
Tnx a lot
HeY, ThErE iS a NeW uPdAtE oF mE?!?!!? lol
🙂
th🇦🇳🇰🇸
you can still use forks if you need slash cmds... ( disnake , pycord etc)
why slash commands are not working?
You need to wait 1hour after you make a new slash commands...
I know like that
okk
Or try this... wait a min
:/
Did you imported ```python
from discord_slash import SlashCommand
did :/
Ctx is context
yes but i saw docs
how do i get channel id? like message.content.id
So I guess it's not that important
i dont know if that work
Do ctx.channel.id
or message
Ok
@bot.command()
async def channel(ctx):
print(ctx.channel.id)
thanks
🙂
uh its getting the channel id?
Yes
i want the message id, sorry i was typo
Ok
Replace channel with message
yea
The message ID.
ok
@bot.command()
async def msg(ctx):
print(ctx.message.id)
how can we build our own api?
Use a web framework that makes APIs or simply create basic raw PHP or similar files and host it on a web server
oh ok
Depending on the language(s) you know there is definitely a framework to make web applications, just search it up
Or try this. you will see everything of message.
@bot.event
async def on_message(msg)
print(msg)
Haha. It's not useful. but if it's test bot..
ok
Than you get a message like
<Message id=896630045731336233 channel=<TextChannel id=888569645047636002 name='일반' position=0 nsfw=False news=False category_id=888569645047636000> type=<MessageType.default: 0> author=<Member id=853955303535804436 name='이도열' discriminator='5785' bot=False nick=None guild=<Guild id=||Private!|| name='||Private!||' shard_id=None chunked=False member_count=4>> flags=<MessageFlags value=0>>
it will print <class Object at smth discord.Message>
hm
okay that's true
"""Handling errors"""
if isinstance(error, commands.CommandNotFound):
print("Ignoring one Command not found error.")
elif isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Please give all the required arguments.")
elif isinstance(error, commands.MissingPermissions):
await ctx.send("Please give me all permissions.\nsend message, embed links, attach files")
else:
print(f"ERROR: {error}")
raise error```
What is the problem in raise error?
Wow 8members in your server
so much xd
first it is ctx, error not error, ctx
second, do raise error(), not raise error
message = embedesc
if "{user.id}" in message:
message = message.replace("{user.id}", "%s" % (user.id))
if "{user.mention}" in message:
message = message.replace("{user.mention}", "%s" % (user.mention))
if "{user.tag}" in message:
message = message.replace("{user.tag}", "%s" % (user.discriminator))
if "{user.name}" in message:
message = message.replace("{user.name}", "%s" % (user.name))
if "{server.name}" in message:
message = message.replace("{server.name}", "%s" % (user.guild.name))
if "{server.membercount}" in message:
message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
try:
embed = discord.Embed(title=embedtitle,description=embedesc)
embed.set_footer(text=embedfooter)
await channel.send(embed=embed)
await ctx.reply('Completed! **Welcome Events** were tested!')
except:
await ctx.reply("Failed! **Welcome Events** were not tested")
SSSSSSSSSSSSMART
variables will not set
got it
!e
message = embedesc
if "{user.id}" in message:
message = message.replace("{user.id}", "%s" % (user.id))
if "{user.mention}" in message:
message = message.replace("{user.mention}", "%s" % (user.mention))
if "{user.tag}" in message:
message = message.replace("{user.tag}", "%s" % (user.discriminator))
if "{user.name}" in message:
message = message.replace("{user.name}", "%s" % (user.name))
if "{server.name}" in message:
message = message.replace("{server.name}", "%s" % (user.guild.name))
if "{server.membercount}" in message:
message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
try:
embed = discord.Embed(title=embedtitle,description=embedesc)
embed.set_footer(text=embedfooter)
await channel.send(embed=embed)
await ctx.reply('Completed! **Welcome Events** were tested!')
except:
await ctx.reply("Failed! **Welcome Events** were not tested")
bruh
No need of doing raise error()
WTFFFFF that ifs are superfluous if there is no {user.id} it just won't replace and won't raise any error, like.... xD
?
raise error works
ctx.author.id?? doesnt exist
ok
user = ctx.author
message = embedesc
if "{user.id}" in message:
message = message.replace("{user.id}", "%s" % (user.id))
if "{user.mention}" in message:
message = message.replace("{user.mention}", "%s" % (user.mention))
if "{user.tag}" in message:
message = message.replace("{user.tag}", "%s" % (user.discriminator))
if "{user.name}" in message:
message = message.replace("{user.name}", "%s" % (user.name))
if "{server.name}" in message:
message = message.replace("{server.name}", "%s" % (user.guild.name))
if "{server.membercount}" in message:
message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
try:
embed = discord.Embed(title=embedtitle,description=embedesc)
embed.set_footer(text=embedfooter)
await channel.send(embed=embed)
await ctx.reply('Completed! **Welcome Events** were tested!')
except:
await ctx.reply("Failed! **Welcome Events** were not tested")
explain hwow that doesnt work
and its not indentation
What's the error code
user = ctx.author
message = embedesc
message = message\
.replace("{user.id}", user.id)\
.replace("{user.mention}", user.mention)\
.replace("{user.tag}", user.discriminator)\
.replace("{user.name}", user.name)\
.replace("{server.name}", user.guild.name)\
.replace("{server.membercount}", user.guild.member_count)
try:
embed = discord.Embed(title=embedtitle,description=message)
embed.set_footer(text=embedfooter)
await channel.send(embed=embed)
await ctx.reply('Completed! **Welcome Events** were tested!')
except:
await ctx.reply("Failed! **Welcome Events** were not tested")```
How's tring if user.id in message
bro what
something wrong?
yes
what?
the variable wont set
wdym?
it still says {user.id}
oh, i know why
message = embedesc
if user.id in message:
message = message.replace("{user.id}", "%s" % (user.id))
if user.mention in message:
message = message.replace("{user.mention}", "%s" % (user.mention))
if user.tag in message:
message = message.replace("{user.tag}", "%s" % (user.discriminator))
if user.name in message:
message = message.replace("{user.name}", "%s" % (user.name))
if server.name in message:
message = message.replace("{server.name}", "%s" % (user.guild.name))
if server.membercount in message:
message = message.replace("{server.membercount}", "%s" % (user.guild.member_count))
try:
embed = discord.Embed(title=embedtitle,description=embedesc)
embed.set_footer(text=embedfooter)
await channel.send(embed=embed)
await ctx.reply('Completed! **Welcome Events** were tested!')
except:
await ctx.reply("Failed! **Welcome Events** were not tested")```
How's this? I maybe wrong
edited
@slate swan
yes
the slashes go in the code??
but if you want to make all these replaces in one line, then they are not needed
yes
k
slash connects the lines
So you need slash
?
What is ehm and nvm
nvm = nevermind
ehm = like... sigh
So I guess this was worng?
^
@bot.command(name="transum")
async def _transum(ctx, link):
message = await ctx.send(':loading:Solving...')
request_response = requests.head(link)
status_code = request_response.status_code
if urlparse(link).hostname == "www.transum.org":
if status_code != 404:
transum_solve(link)
filename = link.encode("utf-8").hex() + ".png"
await message.edit(file=discord.File(filename))
os.remove(filename) if os.path.isfile(filename) else None
else:
await message.edit(content=':error_404:')
else:
await message.edit(content='Specify a transum URL.')
Hi, this is my code for a bot I am making. However, when I run it, and run the command, it throws this error, anyway I can fix it?
File "/home/aarav/Desktop/main.py", line 62, in _transum
await message.edit(file=discord.File(filename))
TypeError: Object of type File is not JSON serializabl
What's the error code?
I must print something...
literally no error
No error?
oh i know what is the problem
edited
i won't explain that dumb...
||HaRd tO FiX ErRoR||
`Hi can someone help with this?
||NoPe||
its not sending
I read the documentation and these are all the parameters
how do I edit a message with a file?
maybe because embedesc is empty?
more code?
how do you get it
How about delating 1st message and send 2nd?
not that?
Well I thought about that but was just confriming if we can edit a message with a file
But users can't edit message to file too
That is true
So I guess bot cann't
yup
HaHAHAH
aPi Of DiScOrD iS nOt SuPpOrTtInG eDiTiNg FiLeS
Good idea, it is png
I use imgur
guess you use felony?
Ok ill try and report back
🙂
@bot.listen()
async def on_member_update(before, after):
if before.guild.premium_subscriber_role not in before.roles and before.guild.premium_subscriber_role in after.roles:
# The member just boosted
await nitrohook.send(file=discord.File('nitro.jpg'))
await nitrohook.send("boosted")
Will this cord work?
I Can't test it because I have no nitro
ah nitrohook is a Webhook.
but not defined
I used dhook for the Webhook
niceeee
Ah. I already did this
nitrohook = Webhook('Private!')
Lol
wt..
and
from dhooks import Webhook, Embed
i , i won't help)
i mean I already made the hook
Ummmm
o-
o-
o-
ok?
o-o-o-0k
||Have I done something wrong to you...? :(||
||If i did I'm so sorry||
it's just weird making webhooks without knowledge of how to define them
webhooks are only in channels, they cant be just like 'Private' you need to get or create it in channel
!pypi dhooks
omg
I see
Noreasons
They are getting an already existing webhook using its url
@dusk pumice
from discord import Webhook, AsyncWebhookAdapter
import aiohttp
async with aiohttp.ClientSession() as session:
webhook = Webhook.from_url('url-here', adapter=AsyncWebhookAdapter(session))
👀
Thank you. I didn't know that
?
\❌
How would I attach a image to my embed from a relative file instead of url?
?
hmm
so instead of
url=http..
I would want
file=img.png
Use imgur
thanks
@still tiger
Didn't knowed that
no
Um ok
my name was felony
A tag is also there lol
!local
Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:
# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")
# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
file = discord.File(f)
When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.
discord.Embed instances have a set_image method which can be used to set an attachment as an image:
embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png") # Filename here must be exactly same as attachment filename.
After this, you can send an embed with an attachment to Discord:
await channel.send(file=file, embed=embed)
This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.
@dusk pumice So it still ives that error when i try to edit an embed with an img
I tried the code, this is what it looks like
AWW.. so sad
WTH
inside a discord bot, i must use either one of BOT or CLIENT right its not possible to use both if not wrong?
Whatever you intialize it as, it also could be imacoolbot or apiudkjqqden
for example bot = commands.Bot(command_prefix='-') could be thisisacoolbot = commands.Bot(command_prefix='-')
Whatever you want, but I think that commands.Bot is better (I chose 3rd way:)
but then you must refrence it as thisisacoolbot not bot if you have set so
cause im merging 2 scripts
one uses
client = discord.Client()
the other uses
client = commands.Bot(command_prefix=">")
causes it not to work
What do u want to do? Can I get some code?
Actually its fine, what I wanted to do isnt possible so I just delete the message and upload another one with a file instead of editing it
Also I have a question, people say to hide the token in an external file, why is this?
good question 
i was thinking either they dont want to show it when showing their code or they want to make some config file for others to change the token easily
Hmm
idk whyd yu use both in the first place tbh
id say yu just use commands.Bot since yu can work with everything that discord.Client provides and also add cmds as needed
would anyone know how to setup a counter with a bot by any chance? as in every time i run it on replit i want the amount of times the code has been ran to show up.
ive already made an array for the test count and setup another global var to be appended to the array when the codes ran but i dont know how to make the new value that was added stay
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
time = datetime.datetime.utcnow().strftime('[%Y/%b/%d - %I:%M %p]')
if after.channel:
if not before.channel and after.channel:
print(f"[+] {member} Joined {after.channel.name[2:]} at {time}")
if before.channel:
if before.channel and not after.channel:
print(f"[-] {member} Left {before.channel.name[2:]} at {time}")
I have this, But when someone moves into another channel, It doesn't tell me, Can someone tell me what's the function for it?
Is there an api to change my bot token? Imagine I could change it if it gets logged somehow
I don't think so...
Shame
Would be cool the eh
Im not sure tho!
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
time = datetime.datetime.utcnow().strftime('[%Y/%b/%d - %I:%M %p]')
if before.channel != after.channel:
if after.channel is None and before.channel is not None:
print(f"[-] {member} Left {before.channel.name[2:]} at {time}")
elif before.channel is None:
print(f"[+] {member} Joined {after.channel.name[2:]} at {time}")
else:
print(f"[+] {member} Moved from {before.channel.name[2:]} to {after.channel.name[2:]} at {time}")```
oh nextcord, then idk
how would you do it normally?
im using discordpy 2.0v
No documentation found for the requested symbol.
This works but, I want to show 3 things (Left, Joined, Moved)
for moved it would be veeery complex
Urgh
Again?
edited @slate swan
only thing i can think of is using SQL
to check wether a user left and re-joined another channel
or plain left
@slate swan no men, you are wrong)
honestly idk how to use on_voice_state_update
Thanks guys!
you're right ngl
i just assumed
I'm not good at this english, what is ngl?
not going to lie
not gonna lie
ok
How do I make a list of all user roles?
!d discord.Member.roles
property roles: List[Role]```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role") that the member belongs to. Note that the first element of this list is always the default [‘@everyone](mailto:'%40everyone)’ role.
These roles are sorted by their position in the role hierarchy.
!pypi nextcord
A Python wrapper for the Discord API forked from discord.py
when i do that it returns
({guild_id: (censor_list)})
wait
code pls?
wrong one one sec
ok
it should return a list
Code:
@client.command()
@commands.has_permissions(manage_messages=True)
async def mute(ctx, member: discord.Member, *, reason=None):
global bot_delete
if not ctx.author.bot:
role = discord.utils.find(lambda r: r.name == 'Muted', ctx.message.guild.roles)
if role not in member.roles:
print(member.roles)
Output:
[<Role id=896648465227055157 name='@everyone'>, <Role id=896653598220492811 name='MEE6'>]
it MUST return a list
so what is wrong?
I thought it would retunr a list like ["admin", "muted", "staff"] etc
no
then how do i make it return a list like that
but you can do it through [role.name for role in member.roles]
let’s be real here.
that worked thank you :)
yes ofc, I used it for logs
should i consider learning it?
putting logs aside
idk
|}p/0;-[-+*9
if you want voice logs: yes , if not: i think no
sorry dust on my keyboard
lol
it feels kinda like spying
so i usually avoid it
how do i get this to be India?....or can i?
str.title()
?
str is the variable
str.title()```
Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.
For example:
```py
>>> 'Hello world'.title()
'Hello World'
``` The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
```py
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
```...
thenks
usueful i never knew it existed
lol
basic string methods, https://www.w3schools.com/python/python_ref_string.asp
nice ty
there is also capitalize
str.capitalize()```
Return a copy of the string with its first character capitalized and the rest lowercased.
Changed in version 3.8: The first character is now put into titlecase rather than uppercase. This means that characters like digraphs will only have their first letter capitalized, instead of the full character.
name = "geeks FOR geeks"
print(name.capitalize())```
@tough wagon :white_check_mark: Your eval job has completed with return code 0.
Geeks for geeks
can you log deleted stickers?
is it possible to append letters to a string like i would do with a list..?
.join()
!d str.join
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") objects. The separator between elements is the string providing this method.
convert it to string first
not ...region.title, it is str(...region).title
show your code
one sec
nice
these are some really basic stuff python can do, i hope you learn these things first before going for discord bots.
worked...
@spring flax
shall do so...thenks
i usually dont use discord bots for aesthetic looking commands
Check the before.stickers and after.stickers in on_guild_update
oh i meant like someone psots a mesage which has a sticker and then deletes the message can you get the sticker that was deleted
good thing, i started coding on python with dpy and all i did is command say and on_message event in first month, so hard without basics)
yeah mb that's not what i meant
yes you can, if you get the deleted message there is stickers attr
A list of sticker items given to the message.
New in version 1.6.
almost all questions are related to dpy 2.0 here
oh thank you
yes, its a waste of time to go for stuff like this without learning the basics first, i too wasted a month or so trying to code a discord bot without even knowing how classes work or what even they are
))
I feel useless
xD
i 100% agree with you sir
Relatable
it would be sticker.format?
nvm it has png attr
sticker.format is it's image
yes
Hello
I have a doubt - I changed my prefix from ! to Flo but can't seem to have space in it. Eg. I have to use Floprefix instead of Flo prefix. How do I solve it?
Server Prefix Sys
oh np
command_prefix='Flo '
he is making a server prefix sys
and there is case_insensitive for this
oh
thats for commands
not the prefix
i've done the server prefix sys once, it worked fine with spaces too, let me find the code one sec
oof, strip_after_prefix then?
hey my bot is not joining the voice channel. here is my code
@client.command(pass_context = True)
async def join(ctx):
channel = ctx.message.author.voice.voice_channel
await client.join_voice_channel(channel)
here is the error
Ignoring exception in command join:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 111, in join
channel = ctx.message.author.voice.voice_channel
AttributeError: 'VoiceState' object has no attribute 'voice_channel'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'VoiceState' object has no attribute 'voice_channel'
Someone please help me
do you even know what that does or are you just spitting random stuff you found
are you talking to me?
maybe, I think im not the worst person here?)
no
well, can you help me with my problem?
its author.voice.channel
it is not voice_channel, it is channel
ok..... imma try both
and client.join_voice_channel is not a thing
and channel.join()
stop copying old code
ok....
here it is, https://github.com/m-y-x-i/Kreklie-discord-bot/blob/main/cogs/server.py
(this project was coded before i knew about classes so i coded anything i could think of so the code is pretty spaghetti looking)
This bot isn't for hosting. I'm just testing discord.py stuff with it. - Kreklie-discord-bot/server.py at main · m-y-x-i/Kreklie-discord-bot
which tutorial shud i watch then?
none
docs
read the docs and experiment yourself
alright thanks I'll check
I actually didn't understood your prefix way lol.
Pretty weird, first the prefix is only one word, second user can write !prefix h! no and it will set space after prefix
Can i use 2 prefix in python?
---I'm back :D
command_prefix can take a list of prefixes
yes
OH really?
yes
yeah the code is weird.
my prefix command works this way:
kkprefix . withspace : . help
kkprefix . : .help
Btw, I have some commands that could also work in my bots DMs but since I changed the way of how my prefix works (I used json for my prefix in different servers so that means command_prefix = get_prefix). Now when I type the command in my bots DM, it gives the following error:
raise TypeError("command_prefix must be plain string, iterable of strings, or callable "
TypeError: command_prefix must be plain string, iterable of strings, or callable returning either of these, not NoneType
and also this it how it works:
@client.command()
async def help(ctx):
await ctx.message.add_reaction("📭")
def check(m):
if m.author == ctx.author and not ctx.guild:
return True
you should change your code of get_prefix func
How can I use proxy for my discord bot as sometime replit gets rate limited and my bot gets blocked temporarily
it returns None because DM guild is none

oh yeah
..
is it replit
Indeed
???
doesn't metter
replit uses shared ip, so it may get rate limited any time and secondly replit has a very easy to use database that will get you rid of json
Yes I have used the replit db once

alright
your token will get ratelimited not ip, all the tokens from your acc won't work
oh
so no way to bypass right?
except creating thousands of discord accounts, no

cute
cloudflare bans are ip based
they last for like an hour, so i don’t see why you would want to bypass them
Only this is pending
Because my bot is down since 3 hours 
then stop using replit
thinking so..but you know reasons........
reasons?
There are plenty of very cheaps vps
I mean I am just a student and am not allowed to spend money on vps etc.....
then selfhost
there are kids on discord giving people free hosting by buying one or two vps you may search for them. their service last for like a month or so then most of them get bankrupt
not possible 
then don’t host a bot

@sullen shoal what is the withspace that you are using
it just an function argument
if they type withspace after the prefix, the code will add a space after the prefix. however in my code i forgot to add something so rn if you type anything after the prefix, it will add a white space
so could I use the same with my prefix?
this is still not working
@client.command()
async def join(ctx):
channel = ctx.author.voice.channel
await channel.connect()
https://github.com/m-y-x-i/Kreklie-discord-bot/blob/bcd6119c5f0403938b6348c26847dbe535a396de/cogs/server.py#L20
this line should be,
if withspace and withspace.lower() == 'withspace':
cogs/server.py line 20
if withspace:```
you could
but could you give me an example of how exactly would I have to use it?
here is the error
Ignoring exception in command join:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 111, in join
await channel.connect()
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/abc.py", line 1277, in connect
voice = cls(client, self)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/voice_client.py", line 199, in __init__
raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice
I think it's telling you to import a library
which library?
PyNaCl
opus?
read
wait one sec
btw any idea how i can use strip_after_prefix?
why do you want to use it
to make the command better
what?
okay let me try to give you an example then
lets say x is your db,
def prefix(prefix, space = None):
if space is not None and space.lower() == 'withspace':
x.set(prefix+' ')
else:
x.set(prefix)
how do i use ephemeral messages for my bot? i cant find the lib for that
now if someone does,
.prefix kk
the prefix will be kk
and if .prefix kk withspace
it will be, kk
also since for ephemeral messages to work, they have to respond to an interaction so how do i check if a button is pressed or not
oh understood
wait, since prefix can be a string, why not just do .prefix "kk ", then you dont need the space arg
what even is this
you need to use callback for this
why is it "withspace"
also ^
and ^
you dont have to bump them
most prefix commands arent like that so users may get confused other than that if that works, you could do that
!d discord.ui.Button.callback
await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The callback associated with this UI item.
This can be overriden by subclasses.
could someone send the link for the lib for ephemeral messages
do you not see what I'm redirecting you to?
But I use json rather than dbs. I know it kind of sounds dumb but didn't really needed db so I didn't use it. Only thing is that the .set thing, how do you do that in json
you need a db
Which is better? - MySQL or SQLite
SQLite
postgresql
well i basically in that line tried to add a value to the my db, irl i would do it this was if it was json,
db = {}
db[str(guild.id)] = prefix```
cuz its already included in python
hmm
you should use sqlite for money system in python
thanks for info
but don't really need a money sys
use a db eitherway
I will try something with json though but if I get my head stuck around too long, then well It's time for a db
thanks for the help, I'll try it but first gotta eat lunch
time = datetime.datetime.utcnow().strftime('[%Y/%b/%d - %I:%M %p]')
I have this but, It's 3 hours behind my timezone, How do I fix it please?
Maybe because u did UTC? Idk if that affects anything.
how do i make a command require roles from different servers? im using if statements to check
or i can actually do @commands.has_any_role() but idk how to send an error message if the user doesnnt have any of the roles
why though
is utc time needed?
error handler
ty
fullamount = len(rconpayload)
pamount = 0
amount = 2000
limit = 2000
text = []
while True:
if fullamount >= limit:
text.append(rconpayload[pamount:amount])
fullamount -= limit
pamount += limit
amount += limit
if fullamount <= limit:
text.append(rconpayload[pamount:])
break
for part in text:
await ctx.send(part)```
Okay ik this is techniclly for python, but I made this quick script meant to cut parts of string too long to be sent in a discord message by a bot. So i dont get the "invalid body field" error
Anyone knows how to make python not cut words in half since it reads charactors? not words?
because its utc..?
cuz it does this
split it by space then remove some items of it?
wait so u mean..
"i am myxi".split()[:1]
yeah my timezone is ksa, And there is no ksa in datetime
So like split it at the 2000 charector mark?
character*
near*
Use pytz for timezones
Np
well the logic will be a bit longer than just a simple if statement if you need some advanced splitting
hmm
I think i see what u mena
@sullen shoal does python have an attribute for reading words withing a strng?
or am i gonna have to script that myself
by making it read spaces
?
words are splitted by space right?
correct
just split it by space then its a list of words
Hi, I have a question because I have error handling of command which saves errors to file and I want to get arguments used in command.
So how can I get arguments used in Spectate command from Spectate.error?
For example let's say someone wrote $Spectate br user and there is an error in the function how to save what this person wrote, like: ("br", "user")
My code is:
@Spectate.error
async def on_error(self, ctx: commands.Context, err: commands.CommandError):
if isinstance(err, commands.CommandOnCooldown):
await ctx.send(f"This command is on cooldown. Please try again after {round(err.retry_after, 1)} seconds.")
else:
self.Spectate.reset_cooldown(ctx)
await ctx.send(
f"Unknown error, please try using $desync and $sync again, if it still doesn't work try using this "
f"command later or report this issue using `report` command")
self.LeagueStats.error_log(ctx, traceback.format_exc()) # this function saves error as file.
Split the string, then count the items in the list
Try error.args
you can use ctx.message.content
it returns string &Spectrate br user
@tough wagon ty
Ah, i have an idea in my head on what to do after splitting them like u said
But i just realized this is going to require more then just a couple if statements
A for loop
I feel like im gonna need another for loop here
@lone lichen well ty for answer, but it gave me args of error in particular part of code not the command itself
Yea I thought you needed names of arguments not the ones user put in, my bad
np
30.5% of 1.54MiB at 72.84KiB/s ETA 00:15
Is there something I can do?
@lone lichen alright thank you. I'm gonna have to do some big brain thinking for a second to formulate how im going to count the charectors in each item, then before it passes the charecter limit it cuts the string and save that part to a new list.
? Just iterate through list and count iterations
Ohh you need to count characters for each word?
Yea that will be a bested for loop
Nested*
the code will look spaghetti and i might prolly think of a better sol of it if i try later but heres what in my head,
get the len() of the string, then store it in var, x
then split it by space, iterate over it, do len() on every iteration then len(iteration) - x
when x hits 0, break the loop
ooo that could work
"the code will look spaghetti" indeed
sum([len(item) from item in iterable]) not better?
@slate swan here u go
aw u gave me the code >:C
i wanted to do some big brain thinking
lol
so is this after i split the strng right?
string*
Yes
This will get u total number of characters in a list of strings basically
isnt that just len(string)? :thining
No cus It’ s in a list
If the charectors exceed the charector limit, I can remove that LATEST item and copy the rest into a different list, and with a loop i can automate the this process
Sounds about right?
is sum and summ different 🤔
Yea try that
alr bet
sum(iterable, /, start=0)```
Sums *start* and the items of an *iterable* from left to right and returns the total. The *iterable*’s items are normally numbers, and the start value is not allowed to be a string.
For some use cases, there are good alternatives to [`sum()`](https://docs.python.org/3/library/functions.html#sum "sum"). The preferred, fast way to concatenate a sequence of strings is by calling `''.join(sequence)`. To add floating point values with extended precision, see [`math.fsum()`](https://docs.python.org/3/library/math.html#math.fsum "math.fsum"). To concatenate a series of iterables, consider using [`itertools.chain()`](https://docs.python.org/3/library/itertools.html#itertools.chain "itertools.chain").
Changed in version 3.8: The *start* parameter can be specified as a keyword argument.
also what is summ?
edited
i gotta try somehting hmm
oh ok
Lemme see
it's not different, there is no summ i did a mistake
Ohh lmao
!e
iterable = ['eweef','wfwefw','wfwewf']
s = ''.join(iterable)
print(summ([len(item) from item in iterable]))
print(len(s)```
@sullen shoal :x: Your eval job has completed with return code 1.
001 | File "<string>", line 3
002 | print(summ([len(item) from item in iterable]))
003 | ^
004 | SyntaxError: invalid syntax
oh
for
!e
iterable = ['eweef','wfwefw','wfwewf']
s = ''.join(iterable)
print(summ([len(item) for item in iterable]))
print(len(s)```
@sullen shoal :x: Your eval job has completed with return code 1.
001 | File "<string>", line 4
002 | print(len(s)
003 | ^
004 | SyntaxError: unexpected EOF while parsing
summ working seriously?
gg
!e
iterable = ['eweef','wfwefw','wfwewf']
s = ''.join(iterable)
print(sum([len(item) for item in iterable]))
print(len(s))```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
001 | 17
002 | 17
sum!
Ayo u can do that???
Overcomplicating things episode 324
324 already?
the code they sent basically wont count the whitespaces
Yusss
uh, I forgot about join, dumb me
That's very true.
U could just add len(list) -1 for spaces
Yes?
over xd funny jokes episode 667
It will be the amount of spaces in the original string
Since he used split
huh?
And it splited where whitespaces are
str.strip([chars])```
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or `None`, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:
```py
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
``` The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
!e
iterable = ['eweef','wfwefw','wfwewf']
s = ' '.join(iterable)
print(sum([len(item) for item in iterable]))
oops
No, he wanna count whitespaces that were removed with split function
now lets try that
!e
iterable = ['eweef','wfwefw','wfwewf']
s = ' '.join(iterable)
print(len(s))
print(sum([len(item) for item in iterable]))
print(len(s)-1)```
@sullen shoal :white_check_mark: Your eval job has completed with return code 0.
001 | 19
002 | 17
003 | 18
Lmfao
wtf are you even doing
Bro just do len(original_string)
We overcomplicating shit
im just pointing out that this wont work for all whitespaces in the string
I get it but y even do all that shit if u can do len(string)
if you want the amount of whitespaces removed, just len the original string then strip whitespaces and then len it again and substract to get the amount
yeah ik
He wanted to make system so it splits too long messages and we overcomplicated it so bad
well no if you want to do that, just do, len('wlef fewbkfwf efkwjbfwjf'.replace(' ', ''))
strip can do that?
no
read the first example
it strips from starting and ending only
what?
What is there is 3 whitespaces
!e ```
string = " h"
print(string.strip())
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
h
???
im not talking about that
im talking about all the white spaces in the string, not in index 0 and :-1
!e ```
string = "h e l l o "
print(string.strip())
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
h e l l o
blanket is trying to say his way is more efficent
