#discord-bots
1 messages Β· Page 484 of 1
You just create an async function.
i have 1
@slash.command(
name='channel',
description="the bot create a text and voice channel for the member that executes this command",
guild_ids=test_guilds, options=[
Option("create", "Enter the Channel Name", OptionType.INTEGER),
Option("delete", "Enter the Channel Name", OptionType.INTEGER)
]
)
async def channel(inter, channelname):
guild = ctx.guild
member = ctx.author
name = 'Custom Channels'
category = discord.utils.get(ctx.guild.categories, name=name)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
}
channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
await ctx.channel.purge(limit=1)

channel
but if i have 2 options so can i assign lets say option create to async def create
and option 2 to async def delete
do you want all options to be int?
https://dislashpy.readthedocs.io/en/latest/objects_and_methods.html?highlight=OptionType#optiontype
no cause they will put in a channel name
try the link i linked above
i will
where even is ctx lol
ctx = inter
Can't see anywhere where you have done that.
but i changed it back Xd
@slash.command(
name='channel',
description="the bot create a text and voice channel for the member that executes this command",
guild_ids=test_guilds, options=[
Option("create", "Enter the Channel Name", OptionType.INTEGER),
Option("delete", "Enter the Channel Name", OptionType.INTEGER)
]
)
async def channel(ctx, channelname):
guild = ctx.guild
member = ctx.author
name = 'Custom Channels'
category = discord.utils.get(ctx.guild.categories, name=name)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
}
channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
await ctx.channel.purge(limit=1)
now you see ctx Xd
You can't just change the arg...
why not ?
Because no
ill try
yeah what @cloud dawn said.
That code probably won't work with the error ctx not defined
it has to be an int can ii change INTEGER to STRING
yes
it doesnt work
Ignoring exception in on_socket_response
Traceback (most recent call last):
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1229, in _on_socket_response
await self._process_interaction(payload["d"])
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1387, in _process_interaction
await self._on_slash_command(inter)
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1287, in _on_slash_command
raise err
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_client.py", line 1282, in _on_slash_command
await app_command.invoke(inter)
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_core.py", line 216, in invoke
raise err
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_core.py", line 212, in invoke
await self._maybe_cog_call(self._cog, interaction, interaction.data)
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\slash_core.py", line 37, in _maybe_cog_call
return await self(inter, **params)
File "C:\Users\Robin310\AppData\Local\Programs\Python\Python39\lib\site-packages\dislash\application_commands\core.py", line 72, in __call__
return await self.func(*args, **kwargs)
TypeError: create() got an unexpected keyword argument 'create'```
@slash.command(
name='channel',
description="the bot create a text and voice channel for the member that executes this command",
guild_ids=test_guilds, options=[
Option("create", "Enter the Channel Name", OptionType.STRING),
Option("delete", "Enter the Channel Name", OptionType.STRING)
]
)
async def create(ctx, channelname):
guild = ctx.guild
member = ctx.author
name = 'Custom Channels'
category = discord.utils.get(ctx.guild.categories, name=name)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
}
channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
await ctx.channel.purge(limit=1)
async def delete(ctx, channeltodelete):
guild = ctx.guild
voicechannel = discord.utils.get(guild.voice_channels, name=channeltodelete)
textchannel = discord.utils.get(guild.channels, name=channeltodelete)
if textchannel and voicechannel is not None:
await textchannel.delete()
await voicechannel.delete()
else:
await ctx.send(f'No channels named, "{channel_name}", was found if you think this was an error please contact the staff using Dm support')
i want to assign option create to the create function Xd
For embeds, where can I find the code for color?
wait what?
!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...
thats the code Xd
i think you misunderstood what options does
it just tells you kind of variable it expects
oh
it's not an option to pick from
damn that would have been cool tho
like /channel create channelnamehere
to create a channel
and /channel delete channelname here
to delete the channel
Xd
i mean you can override it by requesting strings instead so you can have any options you want. You have to parse it yourself tho
i ahve a string atm
@slash.command(
name='channel',
description="the bot create a text and voice channel for the member that executes this command",
guild_ids=test_guilds, options=[
Option("create", "Enter the Channel Name", OptionType.STRING),
Option("delete", "Enter the Channel Name", OptionType.STRING)
]
)
async def create(ctx, channelname):
guild = ctx.guild
member = ctx.author
name = 'Custom Channels'
category = discord.utils.get(ctx.guild.categories, name=name)
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(manage_channels=True , read_messages=True),
}
channel = await guild.create_text_channel(channelname, overwrites=overwrites, category=category)
channel = await guild.create_voice_channel(channelname, overwrites=overwrites, category=category)
await ctx.channel.purge(limit=1)
async def delete(ctx, channeltodelete):
guild = ctx.guild
voicechannel = discord.utils.get(guild.voice_channels, name=channeltodelete)
textchannel = discord.utils.get(guild.channels, name=channeltodelete)
if textchannel and voicechannel is not None:
await textchannel.delete()
await voicechannel.delete()
else:
await ctx.send(f'No channels named, "{channel_name}", was found if you think this was an error please contact the staff using Dm support')```
see : Option("create", "Enter the Channel Name", OptionType.STRING),
Option("delete", "Enter the Channel Name", OptionType.STRING)
@slash.command(
name='channel',
description="the bot create a text and voice channel for the member that executes this command",
guild_ids=test_guilds, options=[
Option("action", "Enter what to do", OptionType.STRING),
Option("value", "Enter the value to give to the action", OptionType.STRING)
]
)
async def create(interaction, action, value):
kinda like this
Get a hex code then remove the # and replace it with 0x
Depends on where its located
Ahh, Thanks
open it and keep it open for 24.7
can i use it for mute system
sure ig
my computer cannot open 24/7
r/wooosh
what?
he got wooshed
i need to study online and when i study online i need to keep another closed
try using a server. You have to pay tho
for free?
so that sets the action and the value of the action ?
u can try heroku
what part of You have to pay tho is free?
the end bruvπ
Heroku is fine but you probably should avoid that.
any specific reason π€
i kinda forgot where i read it but heroku said something that they're gonna stop hosting bots since the site is for web hosting that's why you get a link or something
ohh okiee is there any alternative ?
its like a membership so your bot can run 24/7 in a server but dont get like a free fake server because its probably malware and it could make your pc a zombie
probably a raspberry pi is the next cheap and preferable option. If you don't want to pay a subscription
so is there no way to make the options do difrent things ?
yeah thats a good idea
yeah actually
Can I DM you? I have a problem that i need answer to...
like if option = create :
do thing
else:
do other thing
wot ok
why not just make a dedicated command for each action
cause that wont look the same would it Xd
this looks nice
and lets members choose
what they want to do
ohh wait so it does allow multiple options lol. I'm stupid sorry
haha
your original code with 2 options work lol
yeah don't know how to sorry
try looking into subcommands
i cant find anything that works -_-
@commands.Cog.listener()
async def on_raw_message_delete(self,payload):
print(payload)
mydiscord = discord.Guild
async for entry in mydiscord.audit_logs(limit=100):
deleter = entry.user
print(f"{deleter.name} deleted message by {message.author.name}.")
```Why won't this work? The error says missing 'self' on the async line.
it should be a Guild instance not the class
!e ```py
class Foo:
def foo(self): print("foo method")
Foo.foo()```
@lament mesa :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 5, in <module>
003 | TypeError: foo() missing 1 required positional argument: 'self'
is it possible that the bot can give role in a different server and the command is used in different server?
How do I get the guild instance? D:
From my testing - yes.
Client.get_guild
oh lol how ?
since my bot is being run on my computer and is in 2 discords, i can just search both. This is why I write my code to be specific to 1 discord.
but py foo = Foo() foo.foo() will work because now we have initialized the Foo class
or to the discord the command was run in
??
Put your bot in 2 discords.
then run this:
@bot.event
async def on_ready():
print('Bot is ready')
print(bot.guilds)
@client.command()
async def role_add(ctx):
member = ctx.author
guild = 856061274244251658
role = discord.utils.get(guild.roles, id = 856071314740740096)
await member.add_roles(role)
this didnt work
Is your bot in that guild?
yeah
Does your bot have the relevant perms?
do you have intents
yeah
yes
int object has no attribute roles
you need to get the guild object first
oops
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
oh nice
;-;
@commands.Cog.listener()
async def on_raw_message_delete(self,payload):
print(payload)
mydiscord = self.client.get_guild
async for entry in mydiscord.audit_logs(limit=10):
#deleter = entry.user
print(entry)
print(f"{deleter.name} deleted message by {message.author.name}.")
still doesnt work
I don't want to have to specify a guild
get_guild is a function
oh actually
call it
I can specify the guild id π€
and pass in a valid guild id
since payload has the guild id
That's not the issue atm
and delete is not defined
and why are you using VS for python
use word
Heh
Because I like to play on hard mode
Atleast in word you can give every section of code another font and color the text easier.
just pass None
yeah
@commands.Cog.listener()
async def on_raw_message_delete(self,payload):
print(payload)
mydiscord = self.client.get_guild(payload.guild_id)
async for entry in mydiscord.audit_logs(limit=2, action=discord.AuditLogAction.message_delete):
print('{0.user} did {0.action} to {0.target}'.format(entry))
```gives an exception.. But it doesn't tell me what it is ;-;
you got the tb?
!traceback
Please provide a full traceback to your exception in order for us to 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 / 0
ZeroDivisionError: integer division or modulo by zero
The best way to read your traceback is bottom to top.
β’ Identify the exception raised (e.g. ZeroDivisionError)
β’ Make note of the line number, and navigate there in your program.
β’ Try to understand why the error occurred.
To read more about exceptions and errors, please refer to the PyDis Wiki or the official Python tutorial.
lemme get
Message=
Source=C:\Users\<my name>\Desktop\discordbot\Discordbot\Discordbot\cogs\adminlogs.py
StackTrace:
File "C:\Users\<my name>\Desktop\discordbot\Discordbot\Discordbot\cogs\adminlogs.py", line 105, in on_raw_message_delete (Current frame)
async for entry in mydiscord.audit_logs(limit=2, action=discord.AuditLogAction.message_delete):
File "C:\Users\<my name>\Desktop\discordbot\Discordbot\Discordbot\Discordbot.py", line 76, in <module>
bot.run(bottoken)
It's running it's just throwing an exception
what is this?
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
@commands.Cog.listener()
async def on_raw_message_delete(self,payload):
print(payload)
mydiscord = self.client.get_guild(payload.guild_id)
async for entry in mydiscord.audit_logs(limit=2, action=discord.AuditLogAction.message_delete):
print("Hello World")
``` It prints out 'Hello World' twice as expected. But then I get an exception. I could even throw out the log details etc. same error.
Did you forget to await something?
future warning that something will likely deprecate.
yep , but does this error make the bot shutdown?
I am not sure. You got the error you tell me
how do i use discord activities?
No it's just a warning
I mean I don't think so
Use routes
no
raw api?
yes
how do i use the raw api?
Oh guess we're just forgetting me π¦
requests?
@stone palm the raw discord api?
yes
aiohttp
for activities
hmmm
how do i make a simple send message request?
with the raw api?
!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.pydis.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.
Any idea on how to fix my issue? ;-;
No idea
D:
How to close dms with everyone
hmmmmm π€
What do you mean?
user settings
so i just use this like a normal class?
Yeah you can use this.
just define it somewhere and use the function inside it.
this bot: commands.AutoShardedBot should be bot: Union[commands.Bot, commands.AutoShardedBot]
is lavalink against youtube tos?
I use autosharded, also if were doing this you can also add discord.Client
and here too
try:
result = await self.bot.http.request(Route("POST", f"/channels/{voiceChannelID}/invites"), json = data)
except Exception as e:
``` you can except for `HTTPException` an use `e.code`
and your naming is inconsistent
sometimes you follow conventions, sometimes not
hey i was wondering what is wrong with the line 37 in this ```py
import os
import discord
import csv
import random
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
phrases = []
with open("phrases.csv") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
phrases.append(row[1])
client = discord.Client()
@client.event
async def on_ready():
print(f"{client.user} logged in now!")
@client.event
async def on_message(message):
if message.content.startswith("<help"):
await message.channel.send(f"This is turboz a epic beyblade fan .Do not think of me as a bot think of me as a human. I promise I would never take over the world or would I?{message.author} well i am a bot who tells you shower thoughts made by hypreninja or γγ€γγΌεΏθ
his actual name is karthikeyan and Pro Gamer Tejaji his real name is P.S.N.Tejaji type <thought and <joke")
await message.channel.send("")
elif "<thought" in message.content:
response = phrases[random.randint(0, len(phrases) - 1)]
await message.channel.send(response)
elif "<joke" in message.content:
await message.channel.send(f"this is the best joke webbsite {message.author}ever know to man kind -https://rr.noordstar.me/358eda50")
elif "pls" in message.content:
await message.channel.send(f"lol no more of it {message.author}")
await message.delete()
@client.command()
async def kick(ctx,member: discord.Memeber,*,reason="Tried to swim in lava"):
await member.kick(reason=reason)
@client.command
async def ban(ctx,member: discord.Memeber,*,reason="Tried to swim in lava"):
await member.ban(reason=reason)
my_secret = os.environ['TOKEN']
client.run(my_secret)
so like this?```py
@commands.command()
async def activity(self, ctx):
await DiscordTogetherUrlGen.create_link(self, vc.id, "youtube")
i am not sure mate
and this typehint is wrong
async def create_link(self, voiceChannelID: int, option: str) -> str:
if not isinstance(voiceChannelID, (str,int)):
``` voiceChannelID should be typehinted as `Union[str, int]`
!d discord.TextChannel.create_invite
await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates an instant invite from a text or voice channel.
You must have the [`create_instant_invite`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.create_instant_invite "discord.Permissions.create_instant_invite") permission to do this.
same goes for option
guys
https://paste.pythondiscord.com/vovexeruqa.py
check this link - why this Cog doesnt work ?
pls help if u can
Create the object first
vc?
and why are you expecting both int and str when you only need it to be str
if not isinstance(option, (str,int)):
raise TypeError(f"'option' parameter MUST be of type string or integer, not a \"{type(option).__name__}\" type.")
what object?
also {thing!r} exists
self.togetherControl = DiscordTogetherUrlGen(bot)
...
await self.togetherControl.create_link(ctx.author.voice.channel.id, "youtube")
ohh yeah
!e ```py
a = 'abc'
print(f'a = {a!r}')
@hasty iron :white_check_mark: Your eval job has completed with return code 0.
a = 'abc'
blanket i didn't make this code i should've said, this is what i use since it works and if it works it works π
who's the dev?
i have no clue
:O
then where did you get it from
ctrl+c is a powerfull tool
makes no sense
git prob
π
which git doe
yeah, who made the git
i mean
it was 2 months ago i don't know lol
lemme try and search
yes, pls
oh yeah this dude
he has updated the code i see
its still as bad
i'd have to agree
could you make the whole code better and send it here π
No it's fine, either way tips are always nice.
His code is not good but it's not bad bad like it could use some reworks here and there.
yeah, just wanted to try the reworked version lol
you could PR
i stopped with discord.py a month ago
which fork?
eh?
you stopped working with dpy and switched to a dpy fork...?
(a fork with slash commands & interactions)
is that what you mean
||or have you stopped coding bots||
guys
https://paste.pythondiscord.com/vovexeruqa.py
check this link - why this Cog doesnt work ?
pls help if u can
msg = await self.client.fetch_message(messageid)
``` π€ help?
basically in py
you donβt have decorators on your events or commands
whats decorators ?π
How do I grab a message using the message id?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Everything I find doesnt work
Decorators are basically functions that run before a function above the async function you would put @commands.command() and for events you use @commands.Cog.listener()
np
msg = await self.client.fetch_message(messageid)
```Anybody able to help me figure this out?
```py
@commands.Cog.listener()
async def on_raw_message_delete(self,payload):
print("----")
print(payload)
messageid = payload.message_id
channelid = payload.channel_id
msg = await self.client.fetch_message(messageid)
print(msg)
Trying to get the message object using the message id
Why does the error occur?
self.client._connection._get_message(messageid)
that doesn't seem right
how
idk. but what is _connection?
discord.ConnectionState
it's your bot's cache
you can see it in the source code/github
but my bot only caches stuff if it's online
I want to be able to say my message id is '889517885960093786'
and get the contents of that message. if my bot goes offline then the cache is missing.
It's why I am using on_raw_message_delete
!d discord.TextChannel.get_partial_message try this, but i think this also grabs the message from cache, i might be wrong let me see
get_partial_message(message_id, /)```
Creates a [`PartialMessage`](https://discordpy.readthedocs.io/en/master/api.html#discord.PartialMessage "discord.PartialMessage") from the message ID.
This is useful if you want to work with a message and only have its ID without doing an unnecessary API call.
New in version 1.6.
What if I have the channel and had that as an object? could I get the message using the channel? channel = self.client.get_channel(889479625087021106)
sure
channel.get_partial_message(messageid)
i need help on how to use heroku to keep my bot online forever
I made a stats command in my bot, but it is being ignored
Here's the code ```py
@bot.command
async def stats(self, ctx):
guilds = sum(await self.bot.cogs["Communication"].handler("guild_count", self.bot.cluster_count))
channels = sum(await self.bot.cogs["Communication"].handler("channel_count", self.bot.cluster_count))
users = sum(await self.bot.cogs["Communication"].handler("user_count", self.bot.cluster_count))
embed = discord.Embed(title=f"{self.bot.user.name} Statistics", colour=self.bot.primary_colour)
embed.add_field(name="Owner", value=ctx.guild_owner)
embed.add_field(name="Bot Version", value=self.bot.version)
embed.add_field(name="Uptime", value=self.get_bot_uptime(brief=True))
embed.add_field(name="Clusters", value=f"{self.bot.cluster}/{self.bot.cluster_count}")
if ctx.guild:
embed.add_field(name="Shards", value=f"{ctx.guild.shard_id + 1}/{self.bot.shard_count}")
else:
embed.add_field(name="Shards", value=f"{self.bot.shard_count}")
embed.add_field(name="Servers", value=str(guilds))
embed.add_field(name="Channels", value=str(channels))
embed.add_field(name="Users", value=str(users))
embed.add_field(name="CPU Usage", value=f"{psutil.cpu_percent()}%")
embed.add_field(name="RAM Usage", value=f"{psutil.virtual_memory().percent}%")
embed.add_field(name="Python Version", value=platform.python_version())
embed.add_field(name="discord.py Version", value=discord.__version__)
await ctx.send(embed=embed)```
wdym ignored
it shows
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "stats" is not found
u use cogs ?
nah
How can I get a userβs role (for example Staff)?
why do you have self if it's not a cog , and it's @bot.commamd()
!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.
same queastion to him
lol
You can subclass the commands.Bot() class
Thank you π
What use is is to subclass the bot? I see this all over the place
class cog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.lch = bot.get_channel(880884925711126558)
#cmd code
.......
.........
await self.lch.send(embed=em)
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/nsfw.py", line 122, in pgif
await self.lch.send(embed=em,view=msgl(ctx))
AttributeError: 'NoneType' object has no attribute 'send'
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/jishaku/features/invocation.py", line 146, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'send'
self.lch is None
self.bot.get_channel?
ya
same with this
'NoneType' object has no attribute 'send'
are you sure the id is correct
class cog(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.lch = self.bot.get_channel(880884925711126558)
#cmd code
.......
.........
await self.lch.send(embed=em)
```returns Nonetype
this could be an intents issue
ya
oh is it because it is in init
so the bot instance isn't even up yet when the cog is loaded
I've been thinking about that
I'd say that's it
I don't think that works like that
await self.bot.wait_until_ready()
Could we use ^?
the channel is not cached so it wont work so i cant use in class
just get it during the command
u cant
how come
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
hey I have created a spam detection command but it bans member when he spams I don't need ban but if anyone spams the bot should send a message like don't spam or stop spamming
can anyone help?
just replace the part that ban members with a message?
async def on_ready():
await client.change_presence(status=discord.Status.online , activity=discord.Game(" =help ") )
print("Bot is ready")
while True:
print("cleared")
await asyncio.sleep(10)
with open("spam_detection.txt" , "r+") as file:
file.truncate(0)
#spam detection
@client.event
async def on_message(message):
counter = 0
with open("spam_detection.txt", "r+") as file:
for lines in file:
if lines.strip("\n") == str(message.author.id):
counter += 1
file.writelines(f"{str(message.author.id)}\n")
if counter > 5:
await message.guild.ban(message.author, reason="spam")
await asyncio.sleep(1)
print("uh oh")```
i did it shows a error
Can u help?
what error do you get?
its message.channel.send
ok
I t works but when spam it only mentions the user I want the message Don't spam how to code this?
just change the string inside message.channel.send with whatever you want to send
i have a question, i'm trying to do a discord.py bot with GUI with kivy, is that possible? i did a button for turn on the bot, but the app crash.
python file:
py'''
import kivy
import discord
from discord.ext import commands
from discord.ext.commands import bot
from kivy.app import App as app
from kivy.metrics import dp
from kivy.uix.scrollview import ScrollView
from kivy.uix.boxlayout import BoxLayout as box
from kivy.uix.anchorlayout import AnchorLayout as anchor
from kivy.uix.gridlayout import GridLayout as grid
from kivy.uix.stacklayout import StackLayout as stack
from kivy.config import Config
from kivy.uix.widget import Widget
from kivy.uix.scrollview import ScrollView
from kivy.core.window import Window
from kivy.app import runTouchApp
from kivy.uix.button import Button as button
from kivy.properties import StringProperty
class example(grid):
txt = StringProperty("1")
counter = 0
def init(self, **kwargs):
super().init(**kwargs)
def press(self):
self.counter += 1
self.txt = str(self.counter)
bot = discord.ext.commands.Bot(command_prefix="?")
token = "token"
bot.run(token)
'''
how would the bot have a gui on discord?
kv file:
<MainWidget>:
Label:
text: "hi"
Button:
text: "world"
<example>:
cols: 3
Button:
text: "try"
on_press: root.press()
Label:
text: root.txt
oh , its a app that runs the bot
yes
can I convert something to discord.Member like
discord.Member(id)
I'm dumb
nvm
the app dont respond
the bot is on but the app crash
I just had the biggest waste of time in like, ever
I brought the laptop to my uni so I could code while there's nothing happening
then I realized that the syntax wouldn't load without internet
nor I could actually run it and test the code
So I was carrying around this bigass laptop for no reason
Is there any way to check my bots cache?
Just hook your laptop to your mobile data?
or get an internet dongle?
phone was dead
and what even is an internet dongle?
This doesnt work tho. You're deleting the messages in the channel not of specific user
@commands.command()
async def clear_messages(self, ctx, member: discord.Member, amount=10):
await ctx.channel.purge(limit=amount, check=lambda m: m.author == member)
Clears messages from a specific user
Β―_(γ)_/Β―
Someone else told me to do it
so i did and it worked.
By the way, how could I catch the error that's crashing my command?
Tried doing a few tricks on the terminal, but it also doesn't show up
At most, it just shows that it didn't work
Your code editor doesn't crash and throw an error?
Nope, the editor is fine
It's just the command itself that seems to crash for some reason
do a try/except and catch the except?
I already did
Does the whole bot crash or just the command not run?
except Exception as e: # Em caso de erros durante o processamento,
embed.add_field(
name=f'Falha ao recerragar {ext}.' # Erro Γ© anunciado na Embed.
value = e # Natureza do erro Γ© declarada no fim da Embed.```
The command does run
I mean, it shows the initial signs
It just seems to get randomly stuck midway through it
Then you get a blank response?
Yep
idk how to fix that. I have that same issue with a line in my code
I just do try/catch and pass it
ignore it until someone else fixes it for me xD
I can't even ignore it cause it's a major part of my bot
and I absolutely hate having to restart vscode to correct whatever is weird with it π
hi
Welp
Lesson learned, never code without having the IDE pointing out the errors
Jesus
Hello i have problem i do new people join channel and i don't know why in embed user mention look like this :/
discord issue
I mean, technically it still mentions them π
so i can't fix it?
You can change member.mention to member.name
or even do member.name (member.mention)
try:
x = await ctx.guild.create_category('Mailer')
y = await ctx.guild.create_text_channel('Mailer-logs',category=x)
embed = discord.Embed(title="Setup",description=f"Created a private channel {y.mention}, use ``-accessrole[roles]`` give staff access to the channel.",color=0x1793FC)
await ctx.send(embed=embed)
except:
for y.id in all_channels:
await ctx.send('Bot has already been setup')
break```
why doesn't this work
this
it's the same thing
i prefer the first one.
^ same
Now to help @stark bobcat
yee
Are we assuming the indents are correct? coz discord fucked em
okay so this i can't fix yes?
yep intendation is correct
dk how i pasted
u can mention them outside the embed, that will work
What is the output @stark bobcat ?
How?
.send(member.mention, embed=...)
it makes the channel in the catogory
but
BUT?
when the channel alrdy exists it does not send "Bot has already been setup"
but then it is not look good :/
then live with it the way it is
discord embeds are fucked when it comes down to mentions
use member.name instead of member.mention
π€·ββοΈ
it will show the member name
and creates the channel too
yes member name but not ping his
Why not just reverse the order the bot runs the code?
hm wym
well , its a discord issue and noone can change it
okay
Search for the channel/category first and if it exists, yeet out a 'channel exists.' and if not, create it.
other than your cache
i did that
wait let me send full code
@commands.command()
async def setup(self, ctx):
all_channels = []
for guild in self.bot.guilds:
for channel in guild.text_channels:
all_channels.append(channel.id)
try:
x = await ctx.guild.create_category('Mailer')
y = await ctx.guild.create_text_channel('Mailer-logs',category=x)
embed = discord.Embed(title="Setup",description=f"Created a private channel {y.mention}, use ``-accessrole[roles]`` give staff access to the channel.",color=0x1793FC)
await ctx.send(embed=embed)
except:
for y.id in all_channels:
await ctx.send('Bot has already been setup')
break```
intents is correct
wow that's a lot of channel ids
ye lol
lol
ngl this would work so much smoother with a database
two guilds?
This still isn't searching for a channel.
channel
hmm
it does
if i print it
it works
eee how do i say this
for guild in self.bot.guilds:
for channel in guild.text_channels:
all_channels.append(channel.id)
``` This isn't searching for channels or categories. It's simply storing all channel ids
yeah but then i do a loop to check it
for y.id in all_channels:
await ctx.send('Bot has already been setup')
break```
!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.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
What isn't working
one min
!d discord.on_message_delete
discord.on_message_delete(message)```
Called when a message is deleted. If the message is not found in the internal message cache, then this event will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_delete()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_raw_message_delete "discord.on_raw_message_delete") event instead.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Ohh, are you using a class?
You
I think you are, you have self as first param also you have an instance var self.bot
@drifting arrow
look
@commands.command()
async def setup(self, ctx):
all_channels = []
for guild in self.bot.guilds:
for channel in guild.text_channels:
all_channels.append(channel.id)
x = await ctx.guild.create_category('Mailer')
y = await ctx.guild.create_text_channel('Mailer-logs',category=x)
embed = discord.Embed(title="Setup",description=f"Created a private channel {y.mention}, use ``-accessrole[roles]`` give staff access to the channel.",color=0x1793FC)
await ctx.send(embed=embed)
for y.id in all_channels:
print('correct')
break ```
uhh, are you using the stuff they call "cogs"? (I think you are really using classes or copy pasted from somewhere)
ye but at the last i did it correct
Lemme modify your code. uno momento
well yeah, Bot has a method get_channel but still, you haven't cleared the point, are you using cogs
i am using muscle memory
Im making a discord bot for me and my friends to just stay in vc with since rythm is banned but i was wondering how i could add a loop command
i dont have much experience
for playing music which you don't own?
no we don't help with those stuff here
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
@stark bobcat try this
@commands.command()
async def adminlogs2(self, ctx):
all_channels = []
for channel in ctx.guild.text_channels:
all_channels.append(channel.id)
for i in all_channels:
channel = self.client.get_channel(i)
category_exists = False
channel_exists = False
if channel.name == 'Mailer-logs':
channel_exists = True
if category_exists == 'Mailer':
category_exists = True
if category_exists and channel_exists:
print("Category and channel exists")
elif category_exists and channel_exists == False:
print("Category exists but channel does not")
else:
print("Nothing exists. We're doomed.")
@sterile blaze u can check this out https://pypi.org/project/DiscordUtils/
but not recommended
get from spotify library or smth
thanks
ok lemme try
ill try it out anyways
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.pydis.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.
Remove self
no
want me to make it not cogs ver?
because you are not using cogs
discordutils doesnt even show its source code and its very slow
I wouldnt recommend using it tbh
tbh it doesnt matter that much
^^
They also use youtube_dl so that suspicious too
mhm
indeed
is there an error?
https://paste.pythondiscord.com/edugiqatum.py none cogs version
did it work
memberban = [
"884475415538835507",
"792125905526456332",
"884703567926145085",
"835879940485808178"
]
@bot.event
async def on_member_join(member):
if member.id is in memberban:
await member.kick()
channel = bot.get_channel(858699731928219668)
await channel.send(f"{member.mention} is automatisch gekickt, dit persoon staat op onze blacklist.")
if member.id is in memberban:
^
Invalid syntax
cause i started buliding late
wot
and add a little BM await member.send("Kicked coz banned listed")
whats a bm
yos
Bad manners
confusion
But you can only send messages if they're in the discord
It's optional to be bad manners. Looks less professional.
But i'm not a professional person so what do I care? π
fine imma just run it on my discord lol
.r/holdup

@commands.command()
async def adminlogs2(self, ctx):
all_channels = []
all_categories = []
for category in ctx.guild.categories:
all_categories.append(category)
for channel in ctx.guild.text_channels:
all_channels.append(channel.id)
category_exists = False
channel_exists = False
for i in all_channels:
channel = self.client.get_channel(i)
if channel.name == 'mailer-logs':
channel_exists = True
for i in all_categories:
if i.name == 'mailer':
category_exists = True
if category_exists == True and channel_exists == True:
print("Category and channel exists")
elif category_exists == True and channel_exists == False:
print("Category exists but channel does not")
elif category_exists == False and channel_exists == True:
print("Category doesn't exist but channel does exist")
else:
print("Nothing exists. We're doomed.")
``` There we go. Searches for the channel and category.
Just replace the prints in the if statements for whatever you want to happen.
put a ctx param then
add ctx to your cmd params π€¨
ok lemma try
you can even remove a few lines.
change all_channels.append(channel.id) to -> all_channels.append(channel)
remove channel = self.client.get_channel(i)
change if channel.name == 'mailer-logs': to -> if i.name == 'mailer-logs':
Now back to my adminlogs XD
Like 10 more log entries to create \o/
Coz you arent looking for the right category.
I always set my category names to lowercase.
No worries
how would i get the exact cooldown of a command
is it possible to get an emoji's guild name where my bot is not a member of ?
no
@commands.Cog.listener()
async def on_member_update(self, before, after):
print(f'Before: {before}')
print(f'After: {after}')
``` Why isn't this working? D: the before and after aren't changing.
!d discord.ext.commands.Command.cooldown
No documentation found for the requested symbol.
!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.
you mean the retry_after?
you can get the retry after for a context with Command.get_cooldown_retry_after
with a Context arg
lol
k
property commands: Set[discord.ext.commands.core.Command[discord.ext.commands.core.CogT, Any, Any]]```
A unique set of commands without aliases that are registered.
yeh
you dont need to make an api req for that
add discord.Member as an argument for the command , and you can use member.avatar_url and member.name
why isn't on_member_update not triggering on status and activity updates?
check intents
I have my intents and presence set properly
@quartz beacon I've never worked with webhooks so I cant help you
How do I mute someone for a certain amount of time?
and I'm trying to figure out my own shit first π
Oh you're gonna need a database. a background task (loops) and a command
I think itβs possible to mute someone with set_permissions, but whatβs the default time muted when I use this?
i have no idea. I went with the more longer database route
fine
can someone help me
@slate swan i guess.
Interesting, thank you π
The hard part is figuring out how to get the database to load before the cogs π
And then getting the loops to run
That's a common question asked here. So I have that code ready
@commands.command(help='[Sends the avatar of the mentioned user.]')
@commands.is_owner()
async def avatar(self, ctx, *, member: discord.Member):
userAvatar = member.avatar_url
embed = discord.Embed(color = member.color, timestamp = ctx.message.created_at)
embed.set_author(name = f'Avatar of {member}')
embed.set_image(url = userAvatar)
embed.set_footer(text = f'Requested by {ctx.author}', icon_url=ctx.author.avatar_url)
await ctx.send(embed=embed)
Spoonfeeding in not really the best thing to do.
Damn. you broke my spoonfeeding record π¦
I had gone 2 days since the last time someone ree'd at me for doing it
then you had to go and ree at me π¦
Anybody know why on_member_update isn't triggering for statuses/activities? it triggers for everything else
my on_member_join dont work? Anybody know something about that?
@pastel torrent you got intents correct?
whats that mean?
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.
To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.
Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
intents = Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.
!paste
!d discord.Webhook.send
await send(content=..., *, username=..., avatar_url=..., tts=False, ephemeral=False, file=..., files=..., embed=..., embeds=..., allowed_mentions=..., view=..., thread=..., wait=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message using the webhook.
The content must be a type that can convert to a string through `str(content)`.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object.
If the `embed` parameter is provided, it must be of type [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") and it must be a rich embed type. You cannot mix the `embed` parameter with the `embeds` parameter, which must be a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects to send.
avatar_url
@client.command(aliases = ["lb"])
async def leaderboard(ctx,x = 1):
users = await get_bank_data()
leader_board = {}
total = []
for user in users:
name = int(user)
total_amount = users[user]["wallet"] + users[user]["bank"]
leader_board[total_amount] = name
total.append(total_amount)
total = sorted(total,reverse=True)
em = discord.Embed(title = f"Top {x} Richest People" , description = "This is decided on the basis of raw money in the bank and wallet",color = discord.Color(0xfa43ee))
index = 1
for amt in total:
id_ = leader_board[amt]
member = client.get_user(id_)
name = member.name
em.add_field(name = f"{index}. {name}" , value = f"{amt}", inline = False)
if index == x:
break
else:
index += 1
await ctx.send(embed = em)
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
The bot has systems to try and detect if people sent a token
you turned name into an int
what
lemme read your code properly hold up
kk bro
client.getuser(id) isn't this suppose to be client.get_user(id)?
i think that's correct
dpy2 has discord activities
and?
yes
Hi, I'm re-creating (and not forking) discord.py (called Disthon) using the code form discord.py, discord.js and Sapphire framework.
I need programming experts to lend me a hand with the project. If anyone's interested in contributing, please reply to this message
await on_command_error(context, exception)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
The default command error handler provided by the bot.
By default this prints to [`sys.stderr`](https://docs.python.org/3/library/sys.html#sys.stderr "(in Python v3.9)") however it could be overridden to have a different implementation.
This only fires if you do not specify any listeners for command error.
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, your_own_error):
#code
can someone help pls i get this error message
traceback (most recent call last):
File "c:\Users\maxim\Documents\programs\role updator bot\roblox_bot.py", line 54, in <module>
@client.command(description="Unmutes a specified user.")
AttributeError: 'Client' object has no attribute 'command'
import os
client=disnake.Client()
@client.event
async def on_ready():
print(f"logged in as wass ")
@client.event
async def on_message(message):
if message.content.startswith('/bitcoin'):
await message.channel.send('43000')
I am getting an error str object not callable can anyone help?
how do i add a link button to the link which is generated in my the cmd code??
Not in the same cog.
which line
Is there a way you can get all the messages of a channel (there's like 100 max messages in total) and throw it into a text file like a ticket channel log?
If so, how can I do that?
line 11
In different cogs.
embed.add_field(name='Tag:', value=role)``` what do i replace role with
How can I make my bot execute an action, for example send a message every day at an exact time?
use a loop
anyone know about this?
replace role, with the role??
just put like @member
any other better way that doesn't consume so much resources?
jk <@&role_id> @lone aurora
just use a loop lol, its not that intensive
why &role_id
u want to mention to role right
but I don't want to use a loop
yes
so i have to add &?
so use what i put
aight
check if ctx.guild.id == ID OF THE SERVER YOU WANT TO RUN THE COMMAND ON
isnt there a check for exactly this
not sure
could make your own
@client.command()
async def pp69420(ctx):
logs = await ctx.channel.history(limit=None).flatten()
with open('logs.txt', "w") as f:
f.write(logs)
f.close()
await ctx.channel.send(f'{logs}')``` Error: ```py
Traceback (most recent call last):
File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\core.py", line 167, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\jacob\OneDrive\Desktop\Code\Camilla\main.py", line 732, in pp69420
f.write(logs)
TypeError: write() argument must be str, not list
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\bot.py", line 994, in invoke
await ctx.command.invoke(ctx)
File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\core.py", line 894, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\users\jacob\appdata\local\programs\python\python39\lib\site-packages\discord\ext\commands\core.py", line 176, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: write() argument must be str, not list ``` I'm trying to make it to where I get all the messages of a channel into a text file and sending that file. Could I get some guidance, please?
the log var isn't really a variable is a list
so make an string or cycle through the list and insert all the values inside the file
Hmmm
and alse I think they are a list with the message objects not only the content
o ok
always check spelling
thx
did you figure out how to do it?
How can I make my bot execute an action, for example send a message every day at an exact time? (but without using loops if it's possible thx)
@client.command()
async def pp69420(ctx):
logs = await ctx.channel.history(limit=None).flatten()
with open('logs.txt', "w") as f:
f.write(f'logs')
f.close()
with open('logs.txt', "r") as file:
await ctx.channel.send(f'Here it is!', file=discord.File(file, "logs.txt"))``` Kinda, I still don't know how to get the contents of the channel into the file, could I get more help on that, please?
what do you really want? copying all the contents of all the messages of a channel in a text file?
All the contents of a channel and throwing them into a text file, yes
Great π
I still get this lol?
On Replit use the packager
linux or windows?
@jade jolt i tried what you suggested, but this doesn't ping for some reason, im guessing its because of the embed, any fix?
look here how is he doing it --> [#discord-bots message]
You have to ping outside the embed
sigh
oh I didn't realized it was replit hahaha π€¦ββοΈ
What should I do to get the contents of a channel into a text file though? I'm super confused on that part
ok let me think one min
f.write(logs) doesn't work, so yeah just a bit confused
@client.command()
async def pp69420(ctx):
logs = await ctx.channel.history(limit=None).flatten()
with open('logs.txt', "w") as f:
f.write('logs')
f.close()
with open('logs.txt', "r") as file:
await ctx.channel.send(f'Here it is!', file=discord.File(file, "logs.txt"))``` code in case you need it again
!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)
What does console say?
Also, try to refresh your page
Do not help him with that.
yeah that doesn't works basically you invented that part
Oop, oke, sorry
xd true, I'm not sure what I'm doing in that area at all
Do you know what I should do to make it work?
you can turn the list into an string like this:
logs = str(logs)
but this isn't a good practice
mainly in this case because the list not only contains the message content but all the object it self
so you need to iterate through the list and get the message content of each message and then write it inside the file
Doesn't work xd
Hey @hollow agate!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
you can also do f'{logs}'
@client.command()
async def pp69420(ctx):
channellogs = await ctx.channel.history(limit=None).flatten()
logs = str(channellogs)
with open('logs.txt', "w") as f:
f.write(logs)
f.close()
with open('logs.txt', "r") as file:
await ctx.channel.send(f'Here it is!', file=discord.File(file, "logs.txt"))``` It doesn't give me the contents of the message
https://paste.pythondiscord.com/uyoliperob.php-template is what it gives me
pls stop
listen
you need to get the content of each message
because each message is an object
you know what objects are?
don't you
Hey @quartz beacon!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
errors?
is client.get_role(ID)
role = get(message.server.roles, name='CY Army') I think you've invented this line of code
You need to this:
Iterate the list of all the message objects in the channel
get the content of each message -> message.content
then insert that content inside the file (for example you can make an string and concatenate each new message content to the one before separated by an slash or an space)
@client.command()
async def pp69420(ctx):
await ctx.message.delete()
with open("file.txt", "w") as file:
async for message in ctx.history(limit=None):
file.write(str(message.content + "\n"))
with open("file.txt", "rb") as file:
await ctx.channel.send("Your file is:", file=discord.File(file, "transcript.txt"))``` So I was messing around with stuff and this gives me the messages in the channel, how could I flip the messages though since it gives me the most recent to oldest.
π³
write
the 'w' stands for write, like 'r' for read
is for indicating what you wanna do
yw
you need to think that part by your self
think of flipping the list
for example
Can someone help me please
@client.command()
async def beg(ctx):
await open_account(ctx.author)
user = ctx.author
users = await get_bank_data()
earnings = random.randrange(101)
embed = discord.Embed(color=0xff7b00, title="{ctx.author.mention}", description="You Got {earnings} Pieces Of Candy! π")
embed.set_footer(text="Happy Halloween!", icon_url='https://cdn.discordapp.com/icons/838607169074888744/a999fa5973767b1aaea36a3552e9d0c7.png')
await ctx.send(embed=embed)
users[str(user.id)]["wallet"] += earnings
with open("mainbank.json",'w') as f:
json.dump(users,f)``` Whenever i use the command it shows {earnings} instead of the actual earning thing
remember -> f"{var}"
description=f"You Got {earnings} Pieces Of Candy! π") ```
Thank you bro
not only "{var}"
how to make a bot show what discord badges u have ?
bruh just try it
I'll do this later since I believe python has a .reverse function and that'll be fairly easy... How can I make the transcript show who sent the message? ```py
@client.command()
async def pp69420(ctx):
await ctx.message.delete()
with open("file.txt", "w") as file:
async for message in ctx.history(limit=None):
file.write(str(message.content + "\n"))
with open("file.txt", "rb") as file:
await ctx.send("Your file is:", file=discord.File(file, "transcript.txt"))```
Is as simple as this: TRY EVERYTHING BEFORE ASKING
We are not computer how know if it is going to work, and you aren't going to break you pc by coding (you shouldn't)
message.author but you have all this here -> [https://discordpy.readthedocs.io/en/stable/]
@minor kestrelit worked but with the title it said <@Myid> instead of actually pinging me
meber.mention
see it is as simple as that try it and think why it doesn't works, and after being 2 hours thinking google it and if not come here
no, author
π
{author.mention}?
ctx.author returns the member object wich has the member.mention attribute
wat
@wild oak so you can do ctx.author.mention
then?
send code and output pls
read what the file has and then concat what the file had with what you wanted to write and then overwrite it
embed = discord.Embed(color=0xff7b00, title=f"{ctx.author.mention}", description=f"You Got {earnings} Pieces Of Candy! π") ```
cant?
can't yes haha
thats dum lol
nor in footers
why not
π
@quartz beacon you don't need to close the file in an with statement
yea the context manager automatically closes the file for you
because is open while you are using it and then automaticaly closes
@slate swan :warning: Your eval job has completed with return code 0.
[No output]
Same as write but "r"
yeah, it's extremely awkward
The rest think it by your own, need to go
what I noticed if that I write file.readlines() it won't delete it automatically anymore
got me for a month
wot

file.close()
return

with open('logs.txt', "r+") as file:
would be the correct way to do that
why are you even using a txt file
prodigy
youβre pretty much asking for worst divine punishment ever
I luv you
funny joke that makes no sense in this context
can we stay in context?
haha i laughed man
anyways you shouldnβt use a text file
ok you must be trolling or something
a text file acting as a database?
Why is there two with open?, and why are you doing file.close()
that's new
Your using a context manager... Not sure why you are manually closing the file
"why did you kill that person" "why not lmao"
pls use a database like, sqlite3, mongoDB or something that's not a txt file
it's obvious that database or more consistent and efficient than a .txt file
basically same reasons as why you should not use json as a databse
in txt files you have no way of arranging data
please use a database
because itβs not for that purpose
I might set up a database on my raspberry....
i used to store like my bots updates channel in there
it would probably last a day

but i switched to just putting it in the main file
Hey @orchid raptor!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
accept we or at least i wont help..
I would....
it's not our problem
it would just be making more errors for your code
so one guy = everyone?
https://paste.pythondiscord.com/azuletivax.py
error:
if datavip == False: UnboundLocalError: local variable 'datavip' referenced before assignment
Does anyone know what to do?
pls help
sqlite3 is so simple to install and use πΉ just install the application off their website
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

right toxic is "telling people to do something thatβs more efficient and thatβs actually going to help them"
atleast use json if youβre going for txt or no db
i did a json test with my bot and it stopped working in 2 days πΉ
ooof
json's bad
it wouldnt import or get data correctly
I mean
How i can check if user react to specific bot message?
people tell that a json is not a database
and also that you store things in there
which makes me really confused
maybe I'm just missunderstanding
You store static data into json
static meaning not changing, i.e your bot's token. The playing status etc
oh nice
At least that is what I would say about json for storing stuff
that's quite a good explanation
https://youtu.be/HGOBQPFzWKo this might have been one of the most USELESS videos i've ever watched
Take your Python skills to the next level with this intermediate Python course. First, you will get a review of basic concepts such as lists, strings, and dictionaries, but with an emphasis on some lesser known capabilities. Then, you will learn more advanced topics such as threading, multiprocessing, context managers, generators, and more.
π» C...
lmao
Why would someone store their token in json file
check their dpy tutorial
you would cringe tf out
how are arguments an intermediate thing
itβs just another means of storing a token
learn python*
they were speaking a whole bunch of bullshit in that video
making commands in on_message eventπΏ
did they do that?
they said arguments were a difficult thing to learn π
like WHAT
this one has a reason ig
thatβs not even their dpy vid
they used client
Why
client is for making events
bot is a subclass of client that has explicit stuff for commands
explain how you will get this data
How i can check if user react to specific bot message?
#with open('logs.txt', "r+") as old_file:
#with open('logs.txt', "w") as file:
# You can write those two on one file. Let me see if i remember how
with open('logs.txt', "r+") as old_file, open('logs.txt', "w") as file:
??
your using replit, just use the replit database
define a check func
then what are you trying to store it for..
that can be a privacy breach
it is because with required an indented block and you didn't give it one
Why not?
storing peopleβs messages without their consent
use one with
why not in .env
ummm
how i can do it?
excuse me?
Whats the difference from an .env and json file????
Don't need to dig into it deep lol, its just for storing tokens. As long as you don't upload said file it will be fine
In the end its all preference, and I personally store my tokens in a yml file
i forgot this was a discord.py channel for a sec
Choice
I don't store it anywhere else
That's why message intent is getting privileged

only for verified bots and bots planning to get verified
Lost as to why people even log messages
What am I gonna do with that information?
Oh you like saying a certain word cool
people do that?
replit db aint even all that bad
that's messed up
you just cannot change data without deleting the keys and remaking them
I don't know much but .env is a kind of file useful to store tokens specially when your code is open source
.gitignore exists
Take note that even discord doesn't show the content of deleted messages in the audit log. It is against the TOS
most code is going to get uploaded to github anyways
so what about a snipe command?
Uh.. you do know people can still see .env files right???
next message automatically deletes the data
and if your repo is public and has your token visible discord will warn you and unverify that token

