#discord-bots
1 messages · Page 102 of 1
What's wand I want to know how to make cards like this
I think pil should work
whatever u prefer
What do override mean?
And how would it make making bot easy?
@nextcord.slash_command(name="userinfo", description="Shows you a user info of a user!")
@custom_check.has_moderation_and_admin_role_interaction()
@custom_check.If_User_on_UserBlacklist_Slash()
@cooldowns.cooldown(1, 25, bucket=cooldowns.SlashBucket.guild)
async def userinfo(self, interaction: nextcord.Interaction,
_member: nextcord.Member = SlashOption(name="member", description="Please select a member", required=False)):
member = _member or interaction.user
wait = nextcord.Embed(description=f" Please wait. I'm just gathering all the information for you {config.DiscordLoad}", colour=config.red)
await interaction.response.send_message(embed=wait)
de = pytz.timezone('Europe/Berlin')
@nextcord.ui.button(label="Show all Roles", style=nextcord.ButtonStyle.blurple)
async def show_member_roles(interaction: nextcord.Interaction):
embed_roles = nextcord.Embed(description=member.roles)
await interaction.edit_original_message(embed=embed_roles)
button = await show_member_roles(interaction)
await self.universal_log_embed_slash(interaction, _member=_member)
await interaction.edit_original_message(embed=userinfo, view=button)```
He is not sending the button, why?
interaction always comes first
yes thanks!
is it somehow possible to mention a role in the footer of an embed?
it doesn't work in titles
!d discord.Embed - Markdowns don't work in embed titles. Use the url argument if you want to put a hyperlink in the title
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
what catgal just said
valorant = app_commands.Group(name="valorant", description="Valorant Commands")
#@app_commands.command(description='Valorant Commands')
#async def valorant(self, ctx):
# await ctx.send("WIP val commands")
@valorant.command(description='Log in with your Riot acoount')
#@valorant.describe(username='Input username', password='Input password')
# @dynamic_cooldown(cooldown_5s)
async def login(self, interaction: Interaction, username: str, password: str) -> None:
response = ResponseLanguage(interaction.command.name, interaction.locale)
i am trying to make sub commands for app_commands but now they arent appearing when i sync the commands and try to type them out am i mission something? when i print out the sync it isnt in the list
should work like that
You have to defer the interaction if it takes longer than 3 seconds
ctx.defer?
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
There
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 390, in _scheduled_task
await item.callback(interaction)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\information\cog.py", line 197, in button_callback
embed_roles = nextcord.Embed(description=f"{member.roles.join()}\n")
AttributeError: 'list' object has no attribute 'join'
embed_roles = nextcord.Embed(description=f"{member.roles.join()}\n")
await interaction.response.send_message(embed=embed_roles, ephemeral=True) ```
!join
Joining Iterables
If you want to display a list (or some other iterable), you can write:
colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '
However, the separator is still added to the last element, and it is relatively slow.
A better solution is to use str.join.
colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'
An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.
integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
You certainly did not. If you want to join a list of something, you have to use "".join, but you're trying to call it from a list
!e
print("\n".join(("Role 1", "Role 2")))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Role 1
002 | Role 2
Like
embed_roles = nextcord.Embed(description=f"\n".join(member.roles))
but Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Show all Roles' emoji=None row=None>: Traceback (most recent call last): File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\ui\view.py", line 390, in _scheduled_task await item.callback(interaction) File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\information\cog.py", line 197, in button_callback embed_roles = nextcord.Embed(description="\n".join(member.roles)) TypeError: sequence item 0: expected str instance, Role found
The member.roles returns a list of roles, you have to get the mentions from it
if reason == 'Apply To Be A Staff!':
channel = await interaction.guild.create_text_channel(name=f"{interaction.user.display_name} ┃ Ticket", topic=f"{interaction.user.id}")
msg = await interaction.response.send_message(f"**__Ticket Created Successfully__** {channel.mention}", ephemeral=True)
embed = discord.Embed(title=f"{interaction.user} Created A Ticket!", description="Click The Button Below To Close The Ticket!")
embed.add_field(name="סיבה:", value=f"> `{reason}`")
await channel.set_permissions(interaction.guild.default_role, view_channel=False)
await channel.set_permissions(interaction.user, view_channel=True)
interaction.guild.get_role(1010395040385876029): discord.PermissionOverwrite(read_messages=True)
await channel.send(f"{interaction.user.mention} <@&1010395040385876029>", embed=embed)```
File "c:\Users\PC\Desktop\Gal Cohen Bot\main.py", line 584
interaction.guild.get_role(1010395040385876029): discord.PermissionOverwrite(read_messages=True)
^
SyntaxError: illegal target for annotation
what do i change it to then
remove the colon
Yes
And why are you calling Guild.get_role without making a reference?
You need a new line?
like
Anyone know how to use requests to generate accounts on sites?
i want that that role will be able to see that channel
Depends on the site, some use auth some dont making it easy to just use a POST HTTP request
This one does not use any auth
Just a simple account creation
If it doesnt have documentation for the API endpoints you can probably just make an account and check the payload and the endpoint iirc
!rule 5 maybe
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
I doubt you can do anything malicious, e.g creating many accounts for spam
It’s just a quality of life thing
Most endpoints for making accounts have a short ratelimit and some ban with IP and its allot of info you would need to create for so much accounts
but iirc some sites dont like the automation of the creation of accounts
Hey!
I'm making a disocrd bot and i want to add a feature that:
On /suggest they have a True or False statement asking if the suggestion is anonymous.
Example:
im using: pip install -U git+https://github.com/Pycord-Development/pycord
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API
ticket system
Add to the ctx, anonymous: discord.Option(str, choices=[True, False], required=true)
like
dont think he was answering you
I was responding to api
OHH
what do i do
yes yes
likeee its not the whole code
Hey!
I want to make a /generate command that generates a KeyAuth code for a one of the products i own..
How would i do something like that?
OH
what about it lol
shareX
True and False arent statements!
which host?

wdym
i did just as they told in documentation but still im getting error
im guessing you forgot to import it?
discord.Option
That’s what I put and works for me
i got it now ty
from discord.commands import *
use this instead you don't have to type "discord." each time
Ah alright thank you
Try to never use star imports
!pep8
PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.
More information:
• PEP 8 document
• Our PEP 8 song! :notes:
at the end i try to only import which im using to reduce the import cost
You'll also avoid further issues with namespaces
namespace ?
A set of names
ok
In computing, a namespace is a set of signs (names) that are used to identify and refer to objects of various kinds
good
hey how do i set up intents
!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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.
Th- they have different names...
what is streaming in voice channel for an activity.type?
num:discord.Option
Hi!
I'm trying to make a modal for a ticket system. I successfully created the modal and a command to open it with a button.
But, a problem I have is that I have to make a slash command in order to make the button appear (not a problem there), but whenever I stop the bot then launch it again, if I try to use the button again from the previous message, it doesn't work.
What i'm trying to do is to send a message via the button making the button appear, then, if the bot has an update or have to restart, the users can still use the button to make a ticket.
I tried explaining the best way I could, ask me if you didn't understand.
Here's my code:
class Questionnaire(discord.ui.Modal, title="Créez votre ticket !"):
nature = ui.TextInput(label="La nature de votre ticket", required=True, style=discord.TextStyle.short)
explication = ui.TextInput(label="Votre explication", required=True, style=discord.TextStyle.long)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f"Merci ! Votre ticket viens d'être envoyé aux modérateurs!")
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message("Quelque chose s'est produit... Impossible d'envoyer le ticket")
traceback.print_tb(error.__traceback__)
@bot.hybrid_command(name="create_ticket")
async def create_ticket(ctx):
button = Button(label="Créer un ticket", style=discord.ButtonStyle.blurple)
view = View()
view.add_item(button)
async def button_callback(interaction):
await interaction.response.send_modal(Questionnaire())
button.callback = button_callback
await ctx.send(view=view)
How can I do to make the modal open permanently, whatever if the bot restarted or not?
!d discord.TextChannel.purge
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history "discord.Permissions.read_message_history") is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
You can reload the view
When you restart the bot
I see, do I need to make a command or something? Just found this but it's using a command to reload everything. Is there a way to make it automatically?
Nah, you can just place this under on_ready() event py bot.add_view(view=...)
Ah okay
Thank you very much!
Which library
Your bot is an instance of the discord.Intents
how do i delete the sent response in 5 seconds?
like at the bottom
!d discord.Embed.set_image
set_image(*, url)```
Sets the image for the embed content.
This function returns the class instance to allow for fluent-style chaining.
delete_after = 10 i think
Add , delete_after=5) after the "
Nuke g
I tought it was u but u had a weird ass name
embed.set_image() ig
Theres no need for the *,
oh
what is the asterisk for?
You can call that from an embed you're making, like so:
embed = discord.Embed(...)
embed.set_image(url="https://some.image/foo.png")
Can webhooks reply to message?
Ignoring exception in view <DeleteView timeout=60 children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Take Single' emoji=None row=None>:
Traceback (most recent call last):
File "/home/runner/Bot/venv/lib/python3.8/site-packages/disnake/ui/view.py", line 370, in _scheduled_task
await item.callback(interaction)
TypeError: one() takes 2 positional arguments but 3 were given
@discord.ui.button(label="Take Single", style=discord.ButtonStyle.green)
async def one(self, inter):
await self.bot.remove_cards(self.user, self.card, self.q)
await inter.response.send_message(f"Deleted a single duplicate of selected card ({self.card}) from user's inventory.", view=None)
button argument is missing
TypeError: Embed.set_image() takes 1 positional argument but 2 were given
oh i forgor about that one
they said url="link" not directly "link".
no
lol_role = discord.utils.get(ctx.message.guild.roles, name = 'Lol')
await member.add_roles(mute_role)```
how do I change this code so that the role is assigned to the author of command ?
await ctx.author.add_roles(...)
await interaction.user.add_roles(...)
it is also possible for me to just slash command ?
yes
you can do this but remember to respond to the interaction
thanks
No, a message can be ephemeral only when responding to an interaction
https://support.discord.com/hc/en-us/articles/1500000580222-Ephemeral-Messages-FAQ
Q: When can bots send me ephemeral messages?
Bots can only send you this kind of message when you use a Slash Command. If the bot you're using hasn't implemented Slash Commands, they'll have to DM you instead.
this isnt completely correct either
Shh, it's a secret! Ephemeral Messages are a new way for Discord bots to send you a private message without having to send you a DM. You may have received this kind of message before from Clyde, an...
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
!d discord.Interaction.response
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
that's what I've said
Not exactly
and bots can send ephemeral message with user and message command too not only slash command, in general all interaction based things
message can be ephemeral only when responding to an interaction
Bots can only send you this kind of message when you use a Slash Command. If the bot you're using hasn't implemented Slash Commands, they'll have to DM you instead.
Respond to the interaction, instead of just sending a message to the channel the interaction happened in, then you can use the ephemeral kwarg
await interaction.response.send_message(...)
Don't mind the arguments over wording, this happens a lot here :)
btw
I wouldnt say it's wording
a message can be ephemeral also if you're not responding to an interaction, you can send a interaction followup with an ephemeral message too

People make wrappers written in different languages, it's quite easy
Do you mean programming languages, or actual languages?
To followup an interaction with a webhook message
Webhook send methods do have the ephemeral kwarg
!d discord.Interaction.followup
Returns the follow up webhook for follow up interactions.
ephemeral (bool) –
Indicates if the message should only be visible to the user. This is only available to WebhookType.application webhooks. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.
New in version 2.0.
I wonder how they send ephemeral messages
Probably with a flag, just like other messages
And how do they know which user to send it to? arent ephemeral messages per user?
Interaction webhooks are responded to using their token, I'm guessing deciding what user it responds to is done on Discord's end
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
interactions are handled with webhooks
Well then, since it depends on an interaction id to follow up a message with a webhook it would still be considered as responding to a specific interaction
Webhook.async_.py
ig. The response to an interaction usually refers to the initial response
Yeah, but it still behaves like the initial response
Question, what's the width of an interactions token?
How can i check if a user is in my server
Since they are webhooks, I'd say 68
Not sure if it's a static size though
wrote a test view and checked the length of interaction.token, came out to be 214 characters
In documentation its type is a string so how is it a webhook exactly?
Guess it's not 68 then :p
Maybe they depend on interaction type
They don't really have anything documented on discord tokens for things like bots, webhooks, interactions, etc.
^ tokens are merely a string we have to remember to make api requests
only sometimes does it come with extra information, like bot tokens having their application id inside them (was it app id or something else?)
you really don't need to know too much about them
you just need to know where to pass them really
Not sure why they dont get documented, maybe because they're dynamic, but it would still depend what changes about the form of them, e.g width, but that still can get documented, e.g if they ever get changed or a pattern that may be used
well what more would you want from a token? currently they dont carry any information inside them, and whatever you would need to know about it is already part of the interaction payload it came with
The structure can be handy for something like parsing or/and identifying many tokens
After responding to an interaction, how can I delete the message sent?
The users id!
ah right
was that in the discord documentation? i gave it a quick glance but didnt find that diagram
i know there's one for snowflakes
id be concerned if your bot didnt know where a token came from, given that they only come from certain endpoints
@commands.slash_command(name = 'verify', description=": /verify")
async def __clearser__(self, interaction: discord.Interaction):
view = MyView(interaction)
embed = discord.Embed(description= f'**...**', colour=0xF1C40F)
await interaction.response.send_message(embed=embed, view=view, delete_after=60)
view = await view.wait()
verify = discord.utils.get(interaction.response.guild.roles, name = 'Verified')
await interaction.user.add_roles(verify)```
why does the code not work and does not issue a role ?
Do you get an error?
Does your bot have permissions to add roles?
Does verify actually get a value, or does it return your get return None?
Is your bot's role higher than the role you're trying to give to someone?
Traceback (most recent call last):
File "main.py", line 12, in <module>
import discord
File "/home/container/.local/lib/python3.8/site-packages/discord/init.py", line 25, in <module>
from .client import Client
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 53, in <module>
from .webhook import Webhook
File "/home/container/.local/lib/python3.8/site-packages/discord/webhook/init.py", line 11, in <module>
from .async_ import *
File "/home/container/.local/lib/python3.8/site-packages/discord/webhook/async_.py", line 41, in <module>
from ..channel import PartialMessageable
ImportError: cannot import name 'PartialMessageable' from 'discord.channel' (/home/container/.local/lib/python3.8/site-packages/discord/channel.py)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 113, in wrapped
ret = await coro(arg)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 762, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\ToxicPenguin\Desktop\проекты на Python\disocrd bot python\cogs\reg.py", line 30, in __verified__
view = MyView(interaction)
TypeError: __init__() missing 1 required positional argument: 'member'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 755, in process_application_commands
await ctx.command.invoke(ctx)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 312, in invoke
await injected(ctx)
File "C:\Users\ToxicPenguin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\commands\core.py", line 119, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'member'```
@wicked atlas message ERROR
@wicked atlas could ya help with this wrror
This one doesn't have to do with your roles, it looks like you're missing an argument you need to pass into your view
I don't need him to give the role to the mentioned participant I need him to give the role to the author of the command
That is, I wrote the command I got the role
Like I said, this error doesn't have to do with the role part. your MyView object is expecting you pass in a value to the parameter member, but you aren't
.
What lib are you using?
yes
yeah discord.py
alright
Not sure, i looked in discords documentation, nothing, i searched through the github image folder of the official documentation repo, nothing, so i used the image to search for results and i only found the image in issues in github for malicious discord tools
They discuss how the tokens are made but half of the process is missing
@wicked atlas thanks man
class ReName(discord.ui.Modal):
def __init__(self):
super().__init__("Ticket Rename")
self.name = discord.ui.TextInput(
label="New Ticket Name",
min_length=2,
max_length=25
)
self.add_item(self.name)
async def callback(self, interaction: discord.Interaction) -> None:
channel=interaction.channel
await channel.edit(name=self.name.value)
await interaction.response.send_message(f"שיניתי את השם של הטיקט ל: `{self.name.value}`")
class StaffTicket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="rename", custom_id="staff_ticket:rename")
async def rename(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.user.guild_permissions.administrator:
modal=ReName()
await interaction.response.send_modal(modal)
else:
return
```
[2022-10-07 23:50:35] [ERROR ] discord.ui.view: Ignoring exception in view <StaffTicket timeout=900.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='rename' emoji=None row=None>
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 229, in rename
modal=ReName()
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 206, in init
super().init("Ticket Rename")
TypeError: init() takes 1 positional argument but 2 were given```
the modal title has to either be specified as a keyword argument, or in the class inheritance ```py
class MyModal(discord.ui.Modal):
def init(self):
super().init(title='my title')
or
class MyModal(discord.ui.Modal, title='my title'):
...```
ohhh ill try thanks!
oh and for modals the method is called on_submit rather than callback
if you ever forget you can reference the example on the documentation
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.ui.Modal
thank you sm!
@discord.ui.button(label="Transcript", custom_id="staff_ticket:transcript")
async def transcript(self, interaction: discord.Interaction, button: discord.ui.Button):
channel=interaction.channel
messages=await interaction.channel.history(limit=None, oldest_first=True).flatten()
content=[message.content for message in messages]
final= ""
for msg in contents:
msg=msg = "\n"
final=final=msg
with open('transcript.txt', 'm') as f:
f.write(final)
await interaction.response.send_message(file=discord.File(r'transcript.txt'), ephemeral=True)```
do you have any example for this? its not working
whats not working about it? the history() call?
flatten() was removed in 2.0 so it needs to be done with an async for loop instead
https://discordpy.readthedocs.io/en/stable/migrating.html#moving-away-from-custom-asynciterator py messages = [m async for m in channel.history(...)]
same thing you wrote in your history()
you should also use an in-memory file like StringIO BytesIO instead of writing to a file on disk
[2022-10-08 00:09:39] [ERROR ] discord.client: Ignoring exception in on_command_error Traceback (most recent call last): File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 409, in _run_event await coro(*args, **kwargs) File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 155, in on_command_error raise error discord.ext.commands.errors.CommandNotFound: Command "tickets" is not found [2022-10-08 00:09:48] [ERROR ] discord.ui.view: Ignoring exception in view <StaffTicket timeout=900.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Transcript' emoji=None row=None> Traceback (most recent call last): File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task await item.callback(interaction) File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 240, in transcript for msg in contents: TypeError: 'function' object is not iterable
oh
your list is named content but the for-loop says contents
you might as well do async for message in channel.history(): content = message.content and then then write each line to the file
where?
like, to replace the middle half of your code
@discord.ui.button(label="Transcript", custom_id="staff_ticket:transcript")
async def transcript(self, interaction: discord.Interaction, button: discord.ui.Button):
channel=interaction.channel
messages = [msg async for msg in channel.history(limit=None, oldest_first=True)]
contents=[message.content for message in messages]
final= ""
for msg in contents:
msg=msg + "\n"
final=final+msg
with open('transcript.txt', 'msg') as f:
f = open.BytesIO()
f.seek(0)
await interaction.response.send_message(discord_file = discord.File(f, filename='transcript.txt'), ephemeral=True)```
for example: ```py
Make an in-memory file (import io first)
f = io.BytesIO()
async for message in channel.history():
# Turn the message into binary data
data = message.content.encode('utf-8')
# Write the content to the file (your choice on how you want to format it)
f.write(data)
f.seek(0) # reset the file pointer to the start
discord_file = discord.File(f, filename='something.txt')```
uh, you've completely mixed up writing to disk with open() and BytesIO
oh
- make the in-memory file
- write your content to the file
- set the file pointer back to the start
- use it in discord.File to upload the message
i dont know how
also you wrote msg=msg = "\n" and final=final=msg, but i think you meant to add the strings together with + instead
oh oops
@discord.ui.button(label="Transcript", custom_id="staff_ticket:transcript")
async def transcript(self, interaction: discord.Interaction, button: discord.ui.Button):
channel=interaction.channel
messages = [msg async for msg in channel.history(limit=None, oldest_first=True)]
contents=[message.content for message in messages]
final= ""
for msg in contents:
msg=msg + "\n"
final=final+msg
with open('transcript.txt', 'msg') as f:
f = open.BytesIO()
f.seek(0)
await interaction.response.send_message(discord_file = discord.File(f, filename='transcript.txt'), ephemeral=True)```
its just those last 4 lines you need to fix
follow this process, the goal is getting your final message into the in-memory file so you can upload it
Why is if message.guild.id == MY_SERVER_ID: raising an AttributeError: 'NoneType' object has no attribute 'id'
it means message.guild is None, which usually occurs when the message is in a DM
Thanks!
Should I just add an else statement which returns, to avoid getting this error in the future?
Ah, do I need an else statement for my code on the bottom part or keep it exactly as is?
nah the point is removing the else statement
but either way the none check will fix your error
can u teach me how to make a slash command to give a role to a specific user?
Thank you :)
I Badly need to learn.
for discord.py you can read ashley's guide for application commands
https://gist.github.com/Ash-02014/b6f57065f394b54f43666037ade38d32
but first i need to learn how to give a role to a member mb i didnt mean to say specific
giving a role can be done with await Member.add_roles(<role object>), you just need to figure out which member and role you're adding
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
Hey @rich oxide!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Can i have help i cant fix dis error
Traceback (most recent call last):
File "main.py", line 10, in <module>
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
is this pycord?
No
Then it's commands.Bot given you've done from discord.ext import commands
from keep_alive import keep_alive
import discord
import discord.ext
import os
from discord_slash import SlashCommand
import requests
im usin slash
Hey does anyone know why im getting this error
[2022-10-07 19:15:52] [ERROR ] discord.ext.tasks: Unhandled exception in internal background task 'minecraft_count'.
Traceback (most recent call last):
File "C:\Users\kaelm\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\tasks\__init__.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "C:\Users\kaelm\PycharmProjects\358564063833227264\utilsBot\cogs\events\minecraftPlayerCount.py", line 49, in minecraft_count
await channelVar.edit(name=f"🔴 Server offline")
AttributeError: 'NoneType' object has no attribute 'edit'```
When i start my bot, i get a error saying guild is none, when i jsk reload that error magicly fixes itself and i get that
guildVar = self.bot.get_guild(serverID)
print(guildVar)
channelVar = guildVar.get_channel(channel)```
channel is a int, and the channel 10000% exists
!d discord.Guild.get_channel
get_channel(channel_id, /)```
Returns a channel with the given ID.
Note
This does *not* search for threads.
Changed in version 2.0: `channel_id` parameter is now positional-only.
Return type Optional[abc.GuildChannel]
It's a cache lookup and can return None if the channel isnt in cache
what do i use then
!d discord.ext.commands.Bot.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.ext.commands.Bot.fetch_channel
await fetch_channel(channel_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`abc.GuildChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel "discord.abc.GuildChannel"), [`abc.PrivateChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.PrivateChannel "discord.abc.PrivateChannel"), or [`Thread`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Thread "discord.Thread") with the specified ID.
Note
This method is an API call. For general usage, consider [`get_channel()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_channel "discord.ext.commands.Bot.get_channel") instead.
New in version 1.2.
Changed in version 2.0: `channel_id` parameter is now positional-only.
make a check that checks if the channel is in cache if not you make an HTTP request
same error
thats what i tried first
huh
ive never done that in my life
It's just checking datatypes?
not sure what you mean, all im doing is trying to get a channel, id from config, then edit the name, inside a loop
channelvar = self.bot.get_channel(id) or await self.bot.fetch_channel(id)
thats all
Can you show your code?
# Imports
import json
from time import perf_counter
import requests
from discord.ext import commands
from discord.ext import tasks
configjson = open("config.json")
# config should be file name, () gotta be var above
config = json.load(configjson)
serverID = int(config['bot']["serverID"])
minecraftIP = config['minecraft']['serverAddress']
channel = config['channels']['minecraft']['playerCount']
mainColor = config['brandingColors']["mainColor"]
errorColor = config['brandingColors']["errorColor"]
successColor = config['brandingColors']["successColor"]
messages = config['messages']
configjson.close()
# Cog subclass
class MinecraftPlayerCount(commands.Cog):
def __init__(self, bot):
self.bot = (
bot # Allows us to use the bot outside of the __init__ function
)
async def cog_load(self):
self.minecraft_count.start()
async def cog_unload(self):
self.minecraft_count.cancel()
@tasks.loop(minutes=5)
async def minecraft_count(self):
print(124)
server = requests.get(f"https://api.mcsrvstat.us/2/{minecraftIP}")
server = server.json()
print(serverID)
guildVar = self.bot.get_guild(serverID)
print(guildVar)
channelVar = guildVar.get_channel(channel)
if server['online'] == False:
await channelVar.edit(name=f"🔴 Server offline")
else:
await channelVar.edit(name=f"🟢 Players online: {str(server['players']['online'])}")
# Sets up the cog
async def setup(bot):
await bot.add_cog(MinecraftPlayerCount(bot))```
prob should of used a paste bin
but im tired
you never tried what i showed you :))
no i tried that first lol
that was my 3rd try after trying featch and get
with bot
Do you mind testing my method and if it gets an error send it
same error
https://i.leaked-your.info/cp0SR8tu
like i said i already tested it but there i did again
You never used the code i sent.
use this and dont use camelCase!
?? the whole or statement?
it's an expression
nice pfp sarth
tyty
bro what
The funny thing is this isnt the first time I've heard someone call loops homosexual
they are
you cant set bot status for some reason, to get a channel its gay
and i could go on if i didnt have a headake
adding an await bot.wait_until_ready() fixes most of the cache and request related issues :p
your get_channel prob didn't work because cache wasn't ready
and also just saw, you shouldnt be using requests
!pypi aiohttp | use this @indigo pilot
and in your if statement dont check values but check identity
and why are you turning something into a string if an f string already does that, please refactor all of that😭
turning what
and no it dosnt
i know that for a fact since i got a error saying it should be a int !
so unless my python is just magicly broke 😭
never
look at line 49
!f-strings
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
Python will convert it to a string for you.
weird
why?
issues with it
I think you get issues with everything but it's not the things problem, no offense
It's probably not being used right, not something wrong with f strings themselves
well str() fixes it
so its fine lul
It's still slow
that 2ms of time in the loop that runs every 5m wont be noticeable lmao
Thats still good practice, why use a class over literal syntax?
"saying it wont matter" wont make you any better, most developers should care about time complexity and how much time something can add to run time
As said, f strings work fine you just didnt implemented them correctly
welp maybe i did, str has fixed it, dosnt matter
we're just helping you, if you dont want to learn or get better because it works that's your issue and you should reconsider it
False. Premature optimization is the root of all evil
Not all cases require consideration of time complexity or runtime effects, unless it's like really bad
It would depend on the application, most of the time you should care, of course, but most of the time it's just micro optimizations but they can and will stack up, eitheir way python shouldnt be a consideration if your main goal is speed, depending on the application
Can I just add that trying to optimize when you don't know what you're doing is even worse
End up spending hours and hours doing basically nothing
Did this a few months ago 
Hey there, i have a little command that invites a user to a channel, however i want to be able to mention the user. I have the user invited saved as a variable. However if i want to mention the user i need to split it by its name and its discriminator. How can i split my user variable so i can input it into the name = 'Mannequin', discriminator = '8586' section
Because right now i have to specific the user to mention literally
How can i fill in ```name = 'Mannequin', discriminator = '8586'
user.name and user.discriminator I believe
?
This returns the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: get() takes 1 positional argument but 3 were given
You still need to pass them as kwargs
name = user.name, discriminator = user.discriminator
Actually, why are you doing that? You already have the user object.
Or Member object I should say
?
Why are user and amount keyword-only parameters?
Good question indeed
await ctx.send(f"{"Channel" if channel else "Role"} has been updated to {"{}".format(channel.mention) if channel else "{}".format(role.name)}.")
Why am i getting invalid syntax on the period on this line?
You can't use double quotes inside a double quoted string
And why are you interchangedly using .format and f string
Hey!
I am making a discord bot and I have an event that on member join it creates a private vc for them, but i want the bot to check after 10 minutes if the channel is empty and if it is, the bot deletes it otherwise it just does nothing
Current code:
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
is it okey if i use my git page for this
um so whats your error
there is no error... i was asking for a boost in the right direction
ohh ok
u can use time.sleep or await asyncio.sleep
then check if the member is in a voice channel
for pycord/discord.py, i believe discord.Member has an attribute/function for this
how would i make it loop
oh u wanna check every 10 mins
to see if a user is in a voice channel?
if yes u can just use while True or discord.ext.tasks
Installed discord.py using pip install discord.py and it says:
Import “discord” could not be resolved
while True:
if owner in new:
pass
else:
await new.delete()
use tasks
how though
so make a function
@tasks.loop(seconds=300)
async def some_task():
....
yes
how would I make it check if the channel that was made for them is vacant?
pass it to the function
or even better just use an event listener for when ppl disconnect from that vc
and check if the vc is empty then do whatever. no reason to use a tasks for that
nvm doesn't exist wtf.
so i have that using if a member joins a select channel it makes there private one...
how do i get these in my bot's profile
you need a verified discord bot
would this work?
def check(member, before, after):
return member == member.author and before.channel is None and after.channel == new
try:
await bot.wait_for("voice_state_update", check=check, timeout=300)
except TimeoutError:
await new.delete()
return
or just mention the slash cmds in bot's aboutme manually:kek:
that works too
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
how would i define ctx
Using discord.py
Can we name functions? Or they can't be changed?
@client.event
async def on_ready():
print("Bot is online!")```
@client.event
async def ready():
print("Bot is online!")
``` Both will do the same thing?
I mean we are pretty much defining it... so can't we define it in our on way?
The event decorator looks at the name of the function and tries to guess what event it is
If you want another name, use @client.listen("ready")
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
Thanks @rugged shadow
np
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="/", intents=discord.Intents.all())
@client.event
async def on_message(message):
if message.content == "Hello".lower():
await message.channel.send("Hey!")
client.run()
What's the problem here?
"Hello".lower() will always be "hello"
Because of this block of code, my bot won't listen to other events too.
you are overriding the event
so discord.py can't process messages
So..?
place await client.process_commands(message) at the end of your handler
Isn't that good
like if someone types hello or HELLO or HeLlo
Bot will reply
you have it the other way around
it checks if the message content is exactly "hello"
make the content lowercase
Okay
Ah, my bad
i ll try thank you
np
ur pfp ruined my day\night
Why are you lowering the Hello string over using literal syntax that will be static?
noid we already solved it
Does that have any relation to my question?
your question was my question
Im able to run my bot on my local machine but on server it's givin me this error
here is my code:
import asyncio
from aiohttp import ClientSession
async def main():
url = "https://stackoverflow.com/"
async with ClientSession() as session:
async with
is there a way to import the file snake from main.py?
possibly without using from . import
iirc from games import snake
ratelimit
how to update an embed field with button?
this is the code
what does it mean ? how to fix it ?
go to Shell and do kill 1
can someone help i've been asking for 3 days
problems like these are why you should never use replit
so can i just paste all of my codes in another website to make my bot work 24/7 ? and what website can i use
My run token isn’t working even though I know it’s the right token.
any1?
client.run('example.token')
use something like AWS, Linode, or Vultr
is it a user token?
It’s the bot token.
@rugged shadow can you help me too dude?
are you sure it's the token and not the client secret?
so i need to change somethings there like a new code or i can just paste everything from repl.it and it will work the same ? do i need to generate something new ?
100%.
sorry i dont know anything about the new interactions and stuff
AWS for example gives you a machine you can ssh to and place your code there
Are you subclassing view?
I did regenerate it already.
I’ll regenerate it again before I show my code.
view is in a different class and the embed i want to edit is in diffrent
!d discord.Embed.clear_fields
clear_fields()```
Removes all fields from this embed.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 2.0: This function now returns the class instance.
did its still not turning on
i want to keep other fields
run the bot
Guys can anyone suggest me a python package idea
I want to make a python package that help in coding discord bots easy
fetch the fields using embed._todict()
it's like when someone presses the button a embed field will be edited
and readd them
make a package that removes pycord
!d discord.Embed.remove_field
remove_field(index)```
Removes a field at a specified index.
If the index is invalid or out of bounds then the error is silently swallowed.
This function returns the class instance to allow for fluent-style chaining.
Note
When deleting a field by index, the index of the other fields shift to fill the gap just like a regular list.
Changed in version 2.0: This function now returns the class instance.
i want to update it, it isn't possible?
i forgot to ask, what do you mean by "doesn't work"
different views and interactions manager
It says it’s a syntax error.
oh for gods sake
What will this do?
Which I find funny cause it’s worked just fine before.
the one time i didnt ask "what do you mean by doesnt work" it's a syntax error
help ppl who are too lazy to learn oop or monkey patch views
!d discord.Embed.set_field_at - Maybe this? 
set_field_at(index, *, name, value, inline=True)```
Modifies a field to the embed object.
The index must point to a valid pre-existing field. Can only be up to 25 fields.
This function returns the class instance to allow for fluent-style chaining.
@ui.button(label='Upvote', style=discord.ButtonStyle.red)
async def Upvote(self, interaction: discord.Interaction, button: discord.ui.Button):
#update the embed field of the original message
show the error
i just want to update the embed field nothing more
oh noice i forgot about this
yeah but how can i use it in buttons?
I feel like it’s catching the . In the token for some reason.
yeah use what catgal send
how dude
u have the message object right
Your token is visible
that's what i am asking
I already changed it.
Ok
That’s just an example token.
!d discord.Message.embeds
A list of embeds the message has. If Intents.message_content is not enabled this will always be an empty list unless the bot is mentioned or the message is a direct message.
class menu(ui.View):
def __init__(self):
super().__init__()
self.value = None
users = []
@ui.button(label='Upvote', style=discord.ButtonStyle.red)
async def Upvote(self, interaction: discord.Interaction, button: discord.ui.Button):
#update the embed
self.users.append(interaction.user.id)
await interaction.response.edit_message(embed=Embed.set_field_at(1,name="test",value="stt"), view=self)
class SuggestionChannel(commands.Cog):
def __init__(self, client):
self.client = client
@commands.hybrid_command(name="suggest",description="give your suggestion in the server.")
@commands.has_permissions(manage_messages=True)
@app_commands.describe(suggestion="Your Suggestion")
async def suggestion(self, ctx: Context, suggestion: str) -> None:
member = ctx.author
message = ctx.channel
embedx = Embed(color=0x00ff00,timestamp=ctx.message.created_at)
embedx.set_author(name=f"{member.name}#{member.discriminator}",icon_url=member.display_avatar,url=cfxurl)
embedx.set_thumbnail(url=random.choice(thumbnail))
embedx.add_field(name=f"**Username:**",value=member.mention,inline=False)
embedx.add_field(name=f"**Suggested:**",value=suggestion,inline=False)
view = menu()
await message.send(embed=embedx,view=view)```
use this to acess the embed
Can you tell me some more about it?
Like what will this do?
would you mind giving me a short example if possible?
a simple example because i am really new to dpy 2.0 and i don't know much stuff about it
Fixed that and it’s coming back with the same error.
you forgot a parenthesis
) in the "th person to say that" whatever
Just got tunnel vision you know.
class Vote(discord.ui.View):
def __init__(self , timeout):
super().__init__(timeout=timeout)
@ui.button(label="Vote")
async def(self, interaction, _):
embed = (await interaction.original_response()).embeds[0]
embed.set_field_at(n, name=somename, value=somevalue)
await interaction.response.edit_message(embed=embed)
Stare at something long enough and you will never find the solution without an outside look.
lemme try it
doesn't work 😦
No offense, but you didn't get the embeds from the message 
interaction.message can also be used
Where do y'all host your bots? Is there any free good site? I don't wanna pay because there's no profit, I'm making a bot just for fun.
rip 💀
I'm thinking to host from replit to uptimerobot or cronjob.
bro don't copy paste
i don't bro
its pseudo code at best i made
i just don't understand the concept of buttons and stuff man i am still learning it
still doesn't work tho 😢
whats the error?
just says interaction didn't respond
for me it never shows any error
this interaction failed
What do views and interactions manager in discord.py?
u have an error handler?
also u are running with bot.run?
since that has an internal logger
async def main():
await load()
await client.start("Oxo")
asyncio.run(main())```
just try once more and add prints in the callback
what do you mean
i forgot __ for init thats prolly why :p so it was only __init before ;-;
i only used the button function
You simply edited a message but did not respond to the interaction ig
put print()
i did put response tho
that'd print nothing
huh?

wait wait can u show ur current code
lmao
class menu(ui.View):
def __init__(self):
super().__init__()
self.value = None
@ui.button(label='Upvote', style=discord.ButtonStyle.red)
async def Upvote(self, interaction: discord.Interaction, button: discord.ui.Button):
embed = (await interaction.original_response()).embeds[0]
embed.set_field_at(0, name="test", value="test")
await interaction.response.edit_message(embed=embed)```
it's failing to get py embed = (await interaction.original_response()).embeds[0]
^
add a print after each line for debug purpose
embed = (await interaction.message.embeds[0])```?
no remove the await
yeah i did that's why i said
and the '('
done
run
👍
thanks man
anyone got command recommendations?
How would I get my bot to recognize when a specific person sends a message?
!d discord.on_message
discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") is created and sent.
This requires [`Intents.messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.messages "discord.Intents.messages") to be enabled.
Warning
Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
I have an idea of how I want to set it up but I’m unsure of the library function I need to call.
So for on message if I put a users ID in the arguments field it will respond to that specific user?
on_message is an event it is triggered when someone messages something if u want to get the author of the message then u can use author atrribute
That’s a good idea.
if u want to check who is mentioned in the message use message.mentions it will return the list of mentions in the message
The idea is for example if I type a message everytime I type a message it responds.
if message.author.id == id:
Alright thanks.
I’ll figure out the rest from there.
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
good
Guys i want to make a views and interactions manager library
What should It do?
no offense, but i don't think it's a place to ask for that
It's related to discord.py
I wrote the rest of it and it works perfectly.
Thank you.
For me I have difficulty knowing the exact library commands I can use and run for certain results but I have a decent base knowledge of python.
that's good
I learned coding from JCAC.
is that a yt channel?
Joint Cyber Analytics Course.
o
I only had 2 days to learn the very basics of python.
i learnt from yt
You definitely know more than me when it comes to the discord library for sure.
i didn't even learnt the basics i just started with dpy people used to make fun of me for very simple bugs
i learnt the basics along the way lol
after dpy 2.0 struck a lot of commands and functions were changed
i forgot a lot of functions
but now i am trying to learn "em all back
i was a dark sht developer got my acc suspended quite a lot of times
I’ve written poker, blackjack, and dice before on a linux bash shell.
in fact this is my 6 or 7 account
I did it for fun in my spare time while going through JCAC.
that's amazing man
JCAC is a course that condenses a 2 year cyber security degree into 8 months or less.
dark sht developer?
Has a 50% fail rate.
what's a dark sht developer
i had made a selfbot back in 2020 and sold the code to a kid for $450 lol
but now i don't do that stuff just trying to be positive now
450 dafuq
That’s good to hear.
that's an interaction not a message
in your case it would be await msg.message.edit
wait hold on
!d discord.Interaction.message
The message that sent this interaction.
Returns an object responsible for handling responding to the interaction.
A response can only be done once. If secondary messages need to be sent, consider using followup instead.
store the result of send_message into a variable and call edit on that
call someone else to help you i gotta do something rq
ah nvm
show your full command code
Got a syntax error and I am confused what I did wrong specifically.
The error is in the random set.
Put your messages in double quotes
what is msg?
@bot.command()
@commands.has_permissions(administrator=True)
async def saym(ctx, *, saymessage):
await ctx.channel.purge(limit=1)
if saymessage is None:
return await ctx.send("בבקשה תרשום הודעה.")
else:
await ctx.send(saymessage)```
if i say nothing just like !saym it shows error and its not sending בבקשה תרשום הודעה.
Your right.
As soon as I read that I remembered.
That’s how it actually works.
Thanks.
then it should have worked though
@bot.command()
@commands.has_permissions(administrator=True)
async def saym(ctx, *, saymessage):
await ctx.channel.purge(limit=1)
if saymessage is None:
return await ctx.send("בבקשה תרשום הודעה.")
else:
await ctx.send(saymessage)```
if i say nothing just like !saym it shows error and its not sending בבקשה תרשום הודעה.
can someone help me w that
Your ctx.respond return a interaction
https://docs.pycord.dev/en/stable/api.html#discord.ApplicationContext.respond
Use ctx.edit to edit the respond instead
What's the error
discord.ext.commands.errors.MissingRequiredArgument: saymessage is a required argument that is missing.
Your saymessage is an required argument and cannot be none
oh
then can i do smt w that?
You have to give it a default value to make it optional, like:
async def saym(ctx, *, saymessage: str = None):
If saymessage isn't provided, the value of it will be None
Thanks! i will try
If your interaction has to take over 3 seconds to respond, you have to defer it
Perhaps
Put it on top of your function
On top means on top, right before your check definition
await ctx.defer()
def check(m):
...
You didn't send a message, so you can't get a message from it, and I said use ctx.edit to edit the response, not replace ctx.respond with it
Try it
Apparently we were both wrong. So I have to make an array beforehand and set it as the variable for the random choice instead of setting the choices inside the random choice arguement.
I made a coin flip out of it.
You didn't define new_game_ug. For the love of God, read the error
With that in mind I wrote Rock Paper Scissors as well but it doesn’t respond to paper or scissors.
Its the if statement that has the error.
I’m not really worried about it storing the data rn I’m just focusing or working out the kinks and learning from mistakes I make.
Although if I want the bot to perform as I envision it in the future then I will need to use a database.
The or statement isn't doing what you think it's doing
!e
print("a" or "b" or "c")
@winged coral :white_check_mark: Your 3.11 eval job has completed with return code 0.
a
Hmm it’s stopping in the first one.
I have an idea then.
!e
print("a") or ("b") or ("c")
@stable path :white_check_mark: Your 3.11 eval job has completed with return code 0.
a
I’ve never heard of a tuple but I know it’s a type of sequence.
So I think user what you are getting at.
I see*
Ill look it up and learn the difference.
Ok so it uses parentheses instead of brackets.
So how would I implement the in?
if message.content.startswith(in scissors):
I mean clearly that wouldn’t work.
Hey i am wondering how would i get all the permissions somoene has when the person executes a slash command of the bot
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
class AddUser(discord.ui.Modal):
def __init__(self, channel):
super().__init__(title="Add User To A Ticket", timeout=300)
self.channel = channel
self.user = discord.ui.TextInput(
label="User ID",
min_length=2,
max_length=30,
required=True,
placeholder="User ID"
)
self.add_item(self.user)
async def on_submit(self, interaction: discord.Interaction) -> None:
user = interaction.guild.get_member_id
if user is None:
return await interaction.send(f"The ID Is Not Correct, Make Sure The User Is In This Guild!")
overwrite = discord.PermissionOverwrite()
overwrite.read_messages = True
await self.channel.set_permissions(user, overwrite=overwrite)
await interaction.send(f"{user.mention} Has Been Added To The Ticket!")
class StaffTicket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Add User", style=discord.ButtonStyle.green, custom_id="staff_ticket:green")
async def add_user(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(AddUser(interaction.channel))```
```ValueError: target parameter must be either Member or Role
!d discord.ui.Modal - Modal takes no positional argument
class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.
This object must be inherited to create a modal popup window within discord.
New in version 2.0.
Examples...
if message.content.startswith(("Rock","Paper","Scissors")):
...
class AddUser(discord.ui.Modal):
def __init__(self, channel):
super().__init__(title="Add User To A Ticket", timeout=300)
self.channel = channel
self.user = discord.ui.TextInput(
label="User ID",
min_length=2,
max_length=30,
required=True,
placeholder="User ID"
)
self.add_item(self.user)
async def on_submit(self, interaction: discord.Interaction) -> None:
user = interaction.guild.get_member_id
if user is None:
return await interaction.send(f"The ID Is Not Correct, Make Sure The User Is In This Guild!")
overwrite = discord.PermissionOverwrite()
overwrite.read_messages = True
await self.channel.set_permissions(user, overwrite=overwrite)
await interaction.send(f"{user.mention} Has Been Added To The Ticket!")
class StaffTicket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Add User", style=discord.ButtonStyle.green, custom_id="staff_ticket:green")
async def add_user(self, interaction: discord.Interaction, button: discord.ui.Button):
await interaction.response.send_modal(AddUser(interaction.channel))```
```ValueError: target parameter must be either Member or Role
!d discord.TextChannel.set_permissions - It takes Member or Role object, not integer
await set_permissions(target, *, overwrite=see - below, reason=None, **permissions)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sets the channel specific permission overwrites for a target in the channel.
The `target` parameter should either be a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that belongs to guild.
The `overwrite` parameter, if given, must either be `None` or [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite"). For convenience, you can pass in keyword arguments denoting [`Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions") attributes. If this is done, then you cannot mix the keyword arguments with the `overwrite` parameter.
If the `overwrite` parameter is `None`, then the permission overwrites are deleted.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to do this...
property members```
Returns all members that are currently inside this voice channel.
a think a discord.Object can work but im not sure
it won't
i dont understand how to do it
Just pass interaction.user to it
ill try now thanks!
async def on_submit(self, interaction: discord.Interaction) -> None:
user = interaction.user
if user is None:
return await interaction.send(f"The ID Is Not Correct, Make Sure The User Is In This Guild!")
overwrite = discord.PermissionOverwrite()
overwrite.read_messages = True
await self.channel.set_permissions(user, overwrite=overwrite)
await interaction.response.send_message(f"{user.mention} Has Been Added To The Ticket!")
its adding me and now the one i want it to add
What are you trying to do
that if i put the id of the user it will add him to the ticket
!d discord.Guild.get_member - Get the member with the submitted ID
get_member(user_id, /)```
Returns a member with the given ID.
Changed in version 2.0: `user_id` parameter is now positional-only.
!d discord.Interaction.guild - Get the guild before trying to get a member, and don't put \ in the get_member function arguments
property guild```
The guild the interaction was sent from.
oh okay
like
its says that i need to put an id
but if i want to put any id?
Then get the ID from the input you set?
Show your code
`class AddUser(discord.ui.Modal):
def init(self, channel):
super().init(title="Add User To A Ticket", timeout=300)
self.channel = channel
self.user = discord.ui.TextInput(
label="User ID",
min_length=2,
max_length=30,
required=True,
placeholder="User ID",
custom_id="AddUser:staff_ticket"
)
self.add_item(self.user)
async def on_submit(self, interaction: discord.Interaction) -> None:
user = interaction.guild.get_member("AddUser:staff_ticket")
if user is None:
return await interaction.response.send_message(f"The ID Is Not Correct, Make Sure The User Is In This Guild!")
overwrite = discord.PermissionOverwrite()
overwrite.read_messages = True
await self.channel.set_permissions(user, overwrite=overwrite)
await interaction.response.send_message(f"{user.mention} Has Been Added To The Ticket!")
`
That's not how you get an input
Just get from the TextInput you just set
like
!d discord.TextInput.value
self.user?
The default value of the text input.
What?
i dont understnd how
You know how to set class variables but don't know how to get them?
no
That's maybe why you should know about OOP before using dpy. So you basically just get the user you set and get the value from it
user = interaction.guild.get_member(self.user.value)
what do i set as a value
It's the input that the user enters
class AddUser(discord.ui.Modal):
def __init__(self, channel):
super().__init__(title="Add User To A Ticket", timeout=300)
self.channel = channel
self.user = discord.ui.TextInput(
label="User ID",
min_length=2,
max_length=30,
required=True,
placeholder="User ID"
)
self.add_item(self.user)
async def on_submit(self, interaction: discord.Interaction) -> None:
user = interaction.guild.get_member(self.user.value)
if user is None:
return await interaction.response.send_message(f"The ID Is Not Correct, Make Sure The User Is In This Guild!")
overwrite = discord.PermissionOverwrite()
overwrite.read_messages = True
await self.channel.set_permissions(user, overwrite=overwrite)
await interaction.response.send_message(f"{user.mention} Has Been Added To The Ticket!")```
thats what i did for now
Who here is good at making bots maybe help me some to make my bot better
How to know more functions or learn better about discord bots
All I know to do for now is chatting bot
!d discord the docs tells you about all the functions and classds
uh its kinda confusing
the docs tells you about all the functions and classes and you can use !d to search things up in the doc
how can i detect if someone just left the discord server the bot is in?
!d discord.on_member_remove
discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") leaves a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
If the guild or member could not be found in the internal cache this event will not be called, you may use [`on_raw_member_remove()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_member_remove "discord.on_raw_member_remove") instead.
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
ah ok thx
What is activity
What is 1 min
!d discord.Member.bot - Just check if a member is bot or not
property bot```
Equivalent to [`User.bot`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.bot "discord.User.bot")
That returns boolean
No
Check if the member is a bot or not before adding to activity
Guys i want to make a help library for discord.py
Can anyone suggest me any idea?
class AddUser(discord.ui.Modal):
def __init__(self, channel):
super().__init__(title="Add User To A Ticket", timeout=300)
self.channel = channel
self.user = discord.ui.TextInput(
label="User ID",
min_length=2,
max_length=30,
required=True,
placeholder="User ID"
)
self.add_item(self.user)
async def on_submit(self, interaction: discord.Interaction) -> None:
user = interaction.guild.get_member(self.user.value)
if user is None:
return await interaction.response.send_message(f"The ID Is Not Correct, Make Sure The User Is In This Guild!")
overwrite = discord.PermissionOverwrite()
overwrite.read_messages = True
await self.channel.set_permissions(user, overwrite=overwrite)
await interaction.response.send_message(f"{user.mention} Has Been Added To The Ticket!")```
but when u tap on the add user button and pastes an id its says The ID Is Not Correct, Make Sure The User Is In This Guild!
Isn't it just interaction.user?
But then it adds only the one who did the interaction
and i want to it add everyone i want
If member.bot == True
Just use if member.bot == False:
You don't need statement for not
Can someone help me what is the problem with embed.set_thumbail
url kwarg
I want it to be the user avatar
? Ok
It's for !Profile command
That is not relevant
I'm saying url is a keyword only parameter
!d discord.Embed.set_thumbnail
set_thumbnail(*, url)```
Sets the thumbnail for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Changed in version 1.4: Passing `None` removes the thumbnail.
See
Yes
Oh yeah it worked thanks
I maked a discord python test bot but error
What error
``Traceback (most recent call last):
My bot
File "main.py", line 13, in sadutes client runt 10937501855114877821 File: /home/runner/My-bot/veny/1tb/python3,8/site-packages/discord/client.py", line 820, in
run
asyncto.runt runner())
File /nix/store/2vw751379pyyatw32c51bel-python3-3.1.12/1tb/python3.6/async/rm ers.py", line 44, in rui return loop.run until complete main)
File "/htx/store/2ymbw7513h3py yatw32cossibial-python3-3.8.12/11b/python3.8/asyncio/base
Jevents.py", line 616, in run_until_complete
tents
return future.result() File "/home/runner/My-bot/venv/lib/python3.3/site-packages/discord/client.py", line 617, in runner walt self startitolen, reconnect-recomect)
File "/home/runner/Hy-bot/veny/lib/python3.3/site-packages/scord/client.py", line 745, in
awalt self. Login/ token) File "/home/rummer/My-bot/venv/lib/python3.5/site-packages/card/client.py", line 577. Un login
raise TypeError(expected token to be a str, received (token_class___{r} \mstead!}\
TypeError: expected taken to be a str. received class int> Instead
=in``
- more that I could not copy
(Im a mobile dev)
Guys i want to make a help library for discord.py
Can anyone suggest me any idea?
Pls anyone suggest
wth why do u have python 3.3, 3.5 and 3.6
Idk
Cuz
I use a code hosting site and the python section of the site comes preinstalled with all that
So yea
Pls anyone suggest me
I am being bored
Can someone help me??
what do you want to make a library for?
What you mean?
why a library of all things?
if you dont need an ease of life library already, why make one for no reason?
^ no point creating a solution to a problem that doesn't exist
!d discord.Guild.get_role - get_role will return None if the role isn't exist
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
@client.command()
async def help(ctx, member: discord.Member=None):
if member == None:
member = ctx.author
pfp = member.display_avatar
help_embed = discord.Embed(title=f"{pfp} **Command List**", decription="Here\'s the list of commands!", colour=discord.Colour.orange)
help_embed.add_field(name=":game_die:**Games**", value='blackjack')
help_embed.add_field(name=":wrench:**Utility**", value="ping")
await ctx.send(embed=help_embed)
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.```
I don't have any command called `help`.
And if
@client.command()
async def aid(ctx, member: discord.Member=None):
if member == None:
member = ctx.author
pfp = member.display_avatar
help_embed = discord.Embed(title=f"{pfp} **Command List**", decription="Here\'s the list of commands!", colour=discord.Colour.orange)
help_embed.add_field(name=":game_die:**Games**", value='blackjack')
help_embed.add_field(name=":wrench:**Utility**", value="ping")
await ctx.send(embed=help_embed)
``` Then I get this error:
```raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Embed.__init__() got
an unexpected keyword argument 'decription'```
It's description
Whoops..
My mistake, Sorry!
And what about this?
discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias.```
u cant have commands with duplicate name or aliases
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.
there is already an inbuilt help command
How to remove it
to remove it use bot.remove_command('help')
Alright Thanks!
Speaking of inbuilt commands, how many are there?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Expected discord.Colour, int, or None but received method instead.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
@bot.command()
async def mute(ctx, member:discord.Member, time, *, reason):
time = humanfriendly.parse_timespan(time)
await member.edit(timed_out_until=discord.utils.utcnow()+datetime.timedelta(seconds=time))
await ctx.send(f"{member.mention} Has Been Muted For {reason}")
Call the discord.Colour.orange
Oh
My bad again
@naive briar How can I show the pfp of author?
It shows the link.
timedelta is from datetime not datetime.datetime
In title.
Someone pls help me
Because you told it to
How can I tell it to show image?
Where you do want it to?
Top left.
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Set the icon_url
Ohkay, thank you.
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'datetime.timedelta' has no attribute 'datetime'
await member.edit(timed_out_until=discord.utils.utcnow()+timedelta.datetime(seconds=time))
ay yo, I'm struggling with converting GMT iso timestamp into utc unix timestamp so I can use it like:
<t:1665237600:R>
so I need either convert the timezones or add 2 hours to the unix timestamp
how do I do that
What did I say?
# Correct
from datetime import timedelta
print(timedelta(seconds=100))
# Incorrect
from datetime import datetime
print(datetime.timedelta(seconds=100))
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
ohhh
ill try
Guys how can I make a discord.py interactions and views manager library?
works tysm
can someone helpme with add role \ remove role command??
s someone help mee pls
Some ONE HELP ME I maked a discord python test bot but error
Hello @restive dagger, please don't ping anyone even if you need help
only ping moderators if something needs to be moderated
Ok
I recommend seeing #❓|how-to-get-help and claiming a help channel
I claimed one but I was send here cuz my problem has to do with a discord bot
it's fine to ask any Python questions in help channels
just make sure to read the bot's message about how to ask your question
I wanna make first 2 lines of my embad like this. Please help!
Code so far
@client.command()
async def help(ctx, member: discord.Member=None):
if member == None:
member = ctx.author
pfp = member.display_avatar
help_embed = discord.Embed(title=f"{pfp} **Command List**", description="Here\'s the list of commands!", colour=discord.Colour.orange())
help_embed.add_field(name=":game_die:**Games**", value='`blackjack`')
help_embed.add_field(name="\n:wrench:**Utility**", value=" `ping`", inline=False)
await ctx.send(embed=help_embed)
I said use the set_author
oh okay
!d discord.Embed.set_author
set_author(*, name, url=None, icon_url=None)```
Sets the author for the embed content.
This function returns the class instance to allow for fluent-style chaining.
Can you show the code for that
This was my code
pfp = member.display_avatar.url
help_embed = discord.Embed(description="Here\'s the list of commands!", colour=discord.Colour.orange())
help_embed.set_author(name="**Command List**, icon_url=pfp")
```
You didn't set the icon_url
Guys how can I make a discord.py interactions and views manager library?
forogt comma
i mean quotes
Working now
feels stupid i always make silly mistakes
Pls anyone help me if possible
I am goota sleep now 💤
How is that different from the current discord api wrappers?
Hello guys how do i add proxy in my discord bot
See pins in #965291480992321536
Alright.
- Repl.it uses an ephemeral file system.
-
- This means any file you saved via your bot will be overwritten when you next launch.
How it will be over written?
- This means any file you saved via your bot will be overwritten when you next launch.
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
Ah I hate this...
Well I will buy a good service later, for now I am making my bot for "fun" only...
So just run it on vscode or something local
If a bot is just for fun it most likely doesn’t need hosting
Yes, But my ping is high.
I'm using router not lan cable and router is far away...
Anyhow, VS Code is more safe.
Thanks @sick birch !
ephemeral file system?
For instance... If someone has 20k coins, when the bots run next time... the files will be overwritten and his 20k coins will be 0?
“Overwritten” means to just be deleted
You can’t create files with your bot, or any changes will go back to how they were before
Replit 👎 then.
replit does have a simple key-value storage feature
but I would still recommend against it for a motley of other reasons
you can use pythons builtin file read/write system:```py
file = open('file name, including the extension, goes here', 'w')
file.write('new text')```
Read the message before that...
if content_word == "test" and message.author.id in Admins:
map = Update(Faction)
await message.channel.send("{} SHUT THE FUCK UP!",file = discord.File(map).format(message.author.mention))
Im trying to send an image to discord and it wont like it
button = nextcord.ui.Button(label="Show all Roles", style=nextcord.ButtonStyle.blurple)
async def button_callback(interaction):
embed_roles = nextcord.Embed(title="Roles", description="\n".join(reversed([f'> {r.mention}' for r in filter(lambda role: not role.is_default(), member.roles)])))
await interaction.response.send_message(embed=embed_roles, ephemeral=True)
button.callback = button_callback
view = nextcord.ui.View()
view.add_item(button)```
How can one write here a on_timeout?
set button.disabled to True and edit the message with the new view
discord.File accepts a path or the image bytes, not a PIL Image
you can save the Image to an io.BytesIO buffer and pass that to File