I tried to make a function for the tg bot so that the user could click the "Code Request" button, when pressed, he could enter additional information and after that the message was sent to the admin a message about the code request. The problem is that after receiving the message by the admin, the data is erased
Here's the code
#dp.message_handler(text='Запрос кода')
async def start_mailing(message : Message):
user_id = message.from_user.id
if db.cat5_exists(message.from_user.id):
await message.answer(f'Введите количество кодов, или дополнительную информацию:')
await bot_mailing2.info.set()
elif db.cat6_exists(message.from_user.id):
await message.answer(f'Введите количество кодов, или дополнительную информацию:')
await bot_mailing2.info.set()
elif db.cat7_exists(message.from_user.id):
await message.answer(f'Введите количество кодов, или дополнительную информацию:')
await bot_mailing2.info.set()
else:
await bot.send_message(chat_id=message.from_user.id, text=f"Данная функция вам не доступна", reply_markup=menu_button_user)
#dp.message_handler(state=bot_mailing2.info)
async def mailing_text(message : Message, state: FSMContext):
answer = message.text
user_id = message.from_user.id
username = message.from_user.username
mirkip = InlineKeyboardMarkup(row_width=2,inline_keyboard=[[
InlineKeyboardButton(text='Отправить код', callback_data='sendit'),
InlineKeyboardButton(text='Отказать', callback_data='cancel')]])
await state.update_data(info=answer)
await state.update_data(text=user_id)
data = await state.get_data()
print(data)
await bot.send_message(chat_id=ADMIN1, text=f"{username}, запросил код. \nДополнительная информация: {answer}",reply_markup=mirkip)
#await bot.send_message(chat_id=ADMIN2, text=f"{username}, запросил код. \nДополнительная информация: {answer}",reply_markup=mirkip)
#await bot.send_message(chat_id=ADMIN3, text=f"{username}, запросил код. \nДополнительная информация: {answer}",reply_markup=mirkip)
#await bot.send_message(chat_id=SENDER, text=f"{username}, запросил код. \nДополнительная информация: {answer}",reply_markup=mirkip)
#dp.callback_query_handler(text='sendit')
async def start_one(message : Message, state: FSMContext):
user_id = message.from_user.id
await bot.send_message(chat_id=user_id, text='Введите код:')
await bot_mailing2.codes.set()
#dp.message_handler(state=bot_mailing2.codes)
async def get_userId(message: types.Message, state: FSMContext):
answer = message.text
await state.update_data(codes=answer)
data = await state.get_data()
text = data.get('text')
info = data.get('info')
codes = data.get('codes')
print(data)
await state.finish()
it goes like this
{'info': '123', 'text': 5253040087}
{'codes': 'asd'}
but it should be like this
{'info': '123', 'text': 5253040087, 'codes': 'asd'}
Related
components = [
[
Button(label="Open a ticket", style=2, custom_id="Open", emoji="📩")
]
]
await ctx.send(embed=embed, components=components )
while True:
interaction = await client.wait_for("button_click", check = lambda i: i.component.label.startswith("Open"))
overwrites = {
member_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True),
guild.me: discord.PermissionOverwrite(view_channel=True),
ticket_mod_role: discord.PermissionOverwrite(view_channel=True)
}
Embed = discord.Embed(
title="Ticket Created",
description=f"{THIS EMPTY SPACE} Your ticket is created",
)
await interaction.send(content = await interaction.send(embed=Embed), ephemeral=True)
ticket = await ticket_category.create_text_channel(
f"🎫│Ticket-{THIS EMPTY SPACE}", overwrites=overwrites
)
Embed = discord.Embed(
title="Ticket Created",
url="",
description=f"""{ctx.author.name} Wait our staff.""",
color=discord.Color.random()
)
Instead of ctx.author.name (ctx.author is a discord.member class)
Use ctx.author.mention
Docs:
https://discordpy.readthedocs.io/en/stable/api.html?highlight=mention#discord.Member.mention
i've resolved using the library of discord.py (interaction) instead of this i used the object (user.name)
import discord
from discord.ext import commands
from discord_buttons_plugin import *
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='>', intents=intents)
buttons = ButtonsClient(client)
#client.event
async def on_ready():
print("Log : "+str(client.user))
#client.command()
#commands.has_permissions(administrator=True)
async def ticket(ctx):
em = discord.Embed(title="join us",description="To create a ticket react with",emoji={"id": None,"name": "📩","animated": False},color=discord.Color.from_rgb(0,255,0))
await buttons.send(embed=em,channel=ctx.channel.id,
components=[ActionRow([Button(style= ButtonType().Secondary,label = "Create ticket",custom_id = "test1")])])
#buttons.click
async def test1(ctx):
guild = ctx.guild
ch = await guild.create_text_channel(name=f'ticket-{ctx.member}')
await ch.set_permissions(ctx.guild.default_role,view_channel=False,send_messages=False)
await ch.set_permissions(ctx.member,view_channel=True,send_messages=True)
await ctx.reply(f"Ticket created {ch.mention}",flags=MessageFlags().EPHEMERAL)
client.run("token")
I am currently working on something that deletes a users channel when they leave, this was working fine in my test server however now i've put it on the main server it is not functioning. The error I get is shown below: ( I am using diskord.py which is 99% identical to discord.py , only difference being wherever discord should be it says diskord)
Ignoring exception in on_member_remove
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/diskord/client.py", line 428, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/shopside.py", line 157, in on_member_remove
await channeldelete.delete()
AttributeError: 'NoneType' object has no attribute 'delete'
The intended result is it deletes the channel and the log of it in the database
The actual result is neither of these happen and in the logs shown below it says NO to the user having had a channel.
My code:
#commands.Cog.listener()
async def on_member_remove(self, member):
channelfind = cluster["Channels"]["shopside"]
if member.guild.id == shopsideid:
joinedat = diskord.utils.utcnow() - member.joined_at
time = humanize.precisedelta(joinedat, format="%0.0f")
embed = diskord.Embed(title="\u200b", color=0xfc8eac)
embed: Embed = diskord.Embed(
description= f'**{member.mention} left the server**\n:timer: **Joined:**\n{time} ago\n:question:**Shop Channel?**\n`NO`',
color=0xfc8eac
)
embed.set_author(name=member, icon_url=member.avatar.url)
embed.set_thumbnail(url=member.avatar.url)
embed.timestamp = datetime.datetime.utcnow()
embed.set_footer(text=f'ID: {member.id} \u200b ')
memberid = channelfind.find_one({"member_id": member.id})
if memberid is not None:
channelid = memberid['channel_id']
channeldelete = member.guild.get_channel(channelid)
await channeldelete.delete()
deletedata = { "member_id": member.id }
x = channelfind.delete_many(deletedata)
print(x.deleted_count, " documents deleted.")
aembed = diskord.Embed(title="\u200b", color=0xfc8eac)
aembed: Embed = diskord.Embed(
description= f'**{member.mention} left the server**\n:timer: **Joined:**\n{time} ago\n:question: **Shop Channel?**\n`YES.` Channel Name was: {channeldelete.name}',
color=0xfc8eac
)
aembed.set_author(name=member, icon_url=member.avatar.url)
aembed.set_thumbnail(url=member.avatar.url)
aembed.timestamp = datetime.datetime.utcnow()
aembed.set_footer(text=f'ID: {member.id} \u200b ')
log = shopsidelog
await self.bot.get_channel(log).send(embed=aembed)
else:
log = shopsidelog
await self.bot.get_channel(log).send(embed=embed)
pass
Part of the code that the error also refers to:
#diskord.application.slash_command(description="Creates a shop channel", guild_ids=[shopsideid])
#diskord.application.option("member", description="Who is this channel for")
#diskord.application.option("name", description="Channel Name")
#diskord.application.option("category", description="Use the category ID that you want the channel in")
#diskord.application.option("description", description="If no channel description wanted type None")
#diskord.application.option("nsfw", description="True or False")
#commands.has_permissions(manage_messages=True)
async def createchannel(self, ctx, member: diskord.Member, name: str = None, category: diskord.CategoryChannel = None, description: str = None, nsfw: bool = False):
if description == None:
description = " "
category = category
memberrole = ctx.guild.get_role(shopsidemember)
moderator = ctx.guild.get_role(shopsidemod)
channel = await ctx.guild.create_text_channel(name, category=category, )
await channel.set_permissions(ctx.guild.default_role, view_channel=False)
await channel.set_permissions(moderator, view_channel=True, send_messages=True, manage_messages=True)
# SET MOD AND ADMIN ROLE PERMS HERE
await channel.set_permissions(memberrole, view_channel=True, send_messages=True)
await channel.edit(topic=description)
if nsfw == True:
await channel.edit(nsfw=True)
channelid = channel.id
await ctx.send(f"Channel Created: <#{channelid}>")
await channel.send(f"<#{member.id}> Welcome to your channel")
channeldb = cluster["Channels"]["shopside"]
newchannel = {"member_id": member.id, "channel_id": channel.id}
channeldb.insert_one(newchannel)
Any help is appreciated thank you in advance
#client.command()
async def button(ctx):
await ctx.message.delete()
await ctx.send(
"Support Tickets",
components = [
Button(label = "General", style=ButtonStyle.red)
]
)
while True:
interaction = await client.wait_for("button_click", timeout=None, check = lambda i: i.component.label.startswith("General"))
await interaction.respond(content = "Creating The Ticket...")
with open("data.json") as f:
data = json.load(f)
ticket_number = int(data["ticket-counter"])
ticket_number += 1
category_channel = ctx.guild.get_channel(804496358387351562)
ticketlog_channel = ctx.guild.get_channel(819784960823132201)
ticket_channel = await category_channel.create_text_channel(
"ticket-{}".format(ticket_number))
await ticket_channel.set_permissions(ctx.guild.get_role(ctx.guild.id),
send_messages=False,
read_messages=False)
for role_id in data["valid-roles"]:
role = ctx.guild.get_role(role_id)
await ticket_channel.set_permissions(role,
send_messages=True,
read_messages=True,
add_reactions=True,
embed_links=True,
attach_files=True,
read_message_history=True,
external_emojis=True)
await ticket_channel.set_permissions(interaction.author,
send_messages=True,
read_messages=True,
add_reactions=True,
embed_links=True,
attach_files=True,
read_message_history=True,
external_emojis=True)
staff_role = discord.utils.get(ctx.guild.roles, name="Support Team")
data["ticket-channel-ids"].append(ticket_channel.id)
data["ticket-counter"] = int(ticket_number)
with open("data.json", 'w') as f:
json.dump(data, f)
em = discord.Embed(title="Ticket Logs",
description=f"",
color=0x00a8ff)
em.add_field(name="Creator", value=f"{interaction.author.mention}", inline=True)
em.add_field(name="Ticket", value=f"{ticket_channel.name}", inline=True)
time = datetime.now(tz=pytz.timezone('America/Denver'))
formatted = time.strftime("%m/%d/%y, %I:%M %p")
em.set_footer(text=formatted)
await ticketlog_channel.send(embed=em)
await ticket_channel.send(
f'{interaction.author.mention}, please answer the following questions.'
)
await ticket_channel.send('-----------------------------------------------')
def check(message):
return message.channel == ticket_channel and message.author == interaction.author
a = discord.Embed(title="Question 1",
description=f"Is your issue with our forums, discord, or an in-game server? (Please specify which server)",
color=0x00a8ff)
await ticket_channel.send(embed=a)
question1 = await client.wait_for('message', check=check)
b = discord.Embed(title="Question 2",
description=f"What is your IGN? (Forums username)",
color=0x00a8ff)
await ticket_channel.send(embed=b)
question2 = await client.wait_for('message', check=check)
c = discord.Embed(title="Question 3",
description=f"Please explain your issue.",
color=0x00a8ff)
await ticket_channel.send(embed=c)
question3 = await client.wait_for('message', check=check)
d = discord.Embed(title="Question 4",
description=f"Please provide any evidence, if applicable.",
color=0x00a8ff)
await ticket_channel.send(embed=d)
question4 = await client.wait_for('message', check=check)
await ticket_channel.send(f'{question1.content} {question2.content} {question3.content} {question4.content}')
So a little bit of a backstory. I'm currently trying to make a simple ticket system via a button. I would like the button to ask questions once the button is clicked and the channel has been configured correctly. Right now everything works, but only one user at a time (if the user is in the def check(message) process can use the button or it will give them the transaction failed message. I have tried literally anything and everything I can think of to fix this, but haven't had any luck so far. If you could assist me that would be so amazing! Thank you!
I suggest you to don't use the while loop and inside that put client.wait_for()
Create an event function named _on_button_click() and here use a check to see if the message is correct and then ask the question
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I noticed that whenever a command is triggered, the bot usually takes a couple of seconds to respond. Is there any way I can increase the overall speed of the bot? I'm new to programming, so any insight would be greatly appreciated. Here is my code if it helps:
import discord
import os
import random
import praw
from keep_alive import keep_alive
from discord.ext import commands
from discord.ext.commands import Bot
import time
client = commands.Bot(command_prefix='.')
sec_triggers = ['just a sec', 'Just a sec', 'just a second', 'Just a second', 'one sec', 'one second', 'One sec', 'One second']
monke_triggers = ['monke', 'Monke', 'Monkey', 'monkey']
hello_triggers = ['hello there', 'Hello there', 'hello There', 'Hello There']
f_triggers = ['f in the chat', 'F in the chat', 'f in the Chat', 'F in the Chat']
colors = [0xff0000, 0xff3300, 0xff6600, 0xff9900, 0xffcc00, 0xffff00, 0xccff00, 0x99ff00, 0x66ff00, 0x33ff00, 0x00ff00, 0x00ff33, 0x00ff66, 0x00ff99, 0x00ffcc, 0x00ffff, 0x00ccff, 0x0099ff, 0x0066ff, 0x0033ff, 0x0000ff, 0x3300ff, 0x6600ff, 0x9900ff, 0xcc00ff, 0xff00ff, 0xff00cc, 0xff0099, 0xff0066, 0xff0033]
client.remove_command('help')
#client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="you, Wazowski. Always Watching. Always."))
#client.event
async def on_message(message):
if message.author == client.user:
return
msg = message.content
if any(word in msg for word in monke_triggers):
await message.channel.send(file=discord.File('Reject Humanity, Return to Monke.jpg'))
if any(word in msg for word in sec_triggers):
time. sleep(1)
await message.channel.send("It's been one second")
if any(word in msg for word in hello_triggers):
await message.channel.send(file=discord.File('General_Kenobi.gif'))
if any(word in msg for word in f_triggers):
mention = message.author.name
await message.channel.send(f"{mention} had paid their respects.")
if message.content.lower() == 'f' or message.content.lower() == 'F':
mention = message.author.name
await message.channel.send(f"{mention} had paid their respects.")
await client.process_commands(message)
#client.command()
async def catjam(ctx, *, text):
message = f"{text}"
new_message = ""
for char in message:
new_message += f"<a:catjam:800476635655962644>{char}"
new_message += "<a:catjam:800476635655962644>"
await ctx.send(new_message)
await ctx.message.delete()
#client.command()
async def echo(ctx, *, text):
await ctx.send(f"{text}")
await ctx.message.delete()
#client.command()
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, text):
reason = f"{text}"
mention = ctx.message.author.name
pfp = member.avatar_url
em = discord.Embed(title = f"{member} has been kicked.", color = random.choice(colors))
em.add_field(name="Reason:", value=reason)
em.add_field(name="Responsible User:", value=mention)
em.set_thumbnail(url=(pfp))
await member.kick(reason=reason)
await ctx.send(embed=em)
#client.command()
#commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, text):
reason = f"{text}"
mention = ctx.message.author.name
pfp = member.avatar_url
em = discord.Embed(title = f"{member} has been banned.", description= f"__Reason:__ {reason} __Responsible moderator:__ {mention}", color = random.choice(colors))
em.set_thumbnail(url=(pfp))
await member.ban(reason=reason)
await ctx.send(embed=em)
#client.command()
async def comic(ctx):
subreddit = reddit.subreddit("comic")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def joke(ctx):
subreddit = reddit.subreddit("cleanjokes")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
text = random_sub.selftext
em = discord.Embed(title = name, color = random.choice(colors), description = text)
await ctx.send(embed = em)
#client.command()
async def meme(ctx):
subreddit = reddit.subreddit("cleanmemes")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def cat(ctx):
subreddit = reddit.subreddit("catpictures")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def dog(ctx):
subreddit = reddit.subreddit("dogpictures")
all_subs = []
hot = subreddit.hot(limit = 100)
for submission in hot:
all_subs.append(submission)
random_sub = random.choice(all_subs)
name = random_sub.title
url = random_sub.url
em = discord.Embed(title = name, color = random.choice(colors))
em.set_image(url = url)
await ctx.send(embed = em)
#client.command()
async def help(ctx):
em = discord.Embed(color = random.choice(colors))
em.add_field(name='General Commands', value='__help__- Displays this message', inline=True)
await ctx.send(embed = em)
#client.command()
async def server(ctx):
server = ctx.message.guild
roles = str(len(server.roles))
emojis = str(len(server.emojis))
channels = str(len(server.channels))
embeded = discord.Embed(title=server.name, description='Server Info', color=random.choice(colors))
embeded.set_thumbnail(url=server.icon_url)
embeded.add_field(name="Created on:", value=server.created_at.strftime('%d %B %Y at %H:%M UTC+3'), inline=False)
embeded.add_field(name="Server ID:", value=server.id, inline=False)
embeded.add_field(name="Users on server:", value=server.member_count, inline=True)
embeded.add_field(name="Server owner:", value=server.owner, inline=True)
embeded.add_field(name="Server Region:", value=server.region, inline=True)
embeded.add_field(name="Verification Level:", value=server.verification_level, inline=True)
embeded.add_field(name="Role Count:", value=roles, inline=True)
embeded.add_field(name="Emoji Count:", value=emojis, inline=True)
embeded.add_field(name="Channel Count:", value=channels, inline=True)
await ctx.send(embed=embeded)
keep_alive()
client.run(os.getenv('TOKEN'))
(I am adding this part here because it won't let me revise the question otherwise. It tells me "Looks like your post is mostly code, please add some more details". So that is what I am doing, you don't need to read this part.)
This heavily depends on multiple factors.
Your code - I cannot help you without seeing your code, but in any case - a few seconds is a lot and better code wont really change that on a small scale
Your hardware - Also, this is a small part of your bot's performance, but should be negligible
(I think) it is your internet connection. Or maybe Discord's API is having trouble right now.
Of course, there are more factors to it, but it is most likely your internet connection.
If you are locally hosting your bot, then I am pretty much sure that it's your internet. I will show you an example.
Websocket latency when I host locally:
Websocket latency when I host with Heroku:
I experience late response too when I host locally, while with Heroku it's almost instant.
There are some commands which can take much longer than average commands (For example an aiohttp get/post session for uploading an image to Imgur, which takes about 5 seconds when I host locally, but comes almost instantly when I run with Heroku)
I am making a discord.Client. I have a DM command that sends a DM to a specific user, but no message is sent to the user when the command is run, but a message is sent on the Context.channel.
Here is my code:
import discord, asyncio
app = discord.Client()
#app.event
async def on_message(message):
if message.content.startswith('!DM'):
usernotsending = []
content = message.content
msg = await message.channel.send('메시지를 보내고 있습니다!')
i = app.user
# 봇의 모든 유저를 for문으로 적용
for i in app.user:
try:
if i == app.user:
return
# 해당 유저의 DM을 염
await i.create_dm()
# 내용전송
await app.dmchannel.send(content)
# DiscordAPI 에서 오류가 발생했을경우
except discord.HTTPException:
# DM을 보내지 못한 유저 태그 list에 저장
usernotsending.append(f'{i.name}#{i.discriminator}')
messageing = """
아래 유저들에게 메시지를 전송하지 못했습니다!
직접 보내주시거나, 따로 전달을 해드려야됩니다!
"""
for msg in usernotsending:
# message 에 유저 태그 추가
messageing += msg
# 메시지 전송
await msg.edit(content=messageing)
Context is only part of a commands.Bot instance. Your code and your explanation don't seem to match. Assuming you want to DM the author:
import discord
app = discord.Client()
#app.event
async def on_message(message):
if message.content.startswith('!DM'):
try:
await message.author.send(...)
except discord.HTTPException:
...
If you want to DM everyone the bot can see:
import discord
app = discord.Client()
#app.event
async def on_message(message):
if message.content.startswith('!DM'):
for user in app.users:
try:
await user.send(...)
except discord.HTTPException:
...