discord.py ticket commandd - python

I have a ticket command it works but I'm trying to have it create a ticket channel in a specific category
#bot.command()
async def support(ctx, *, reason = None):
guild = ctx.guild
user = ctx.author
await ctx.message.delete() # Deletes the message of the author
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
channel = await guild.create_text_channel(f'Ticket {user}', overwrites=overwrites)
await channel.send(f"{user.mention}")
supem = discord.Embed(title=f"{user} Created a ticket.", description= "", color=0x00ff00)
supem.add_field(name="reason", value=f"``{reason}``")
supem.set_footer(text=f"staff will be with you shortly")
await channel.send(embed=supem)

If you look at the docs here, the create_text_channel function takes a category parameter. If we pass the category to it; it'll create the channel in the specific category.
#bot.command()
async def support(ctx, *, reason = None):
guild = ctx.guild
user = ctx.author
await ctx.message.delete() # Deletes the message of the author
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
# categories are just channels, so `get_channel` will get your category
category = await guild.get_channel(YOUR_CATEGORY_ID)
channel = await guild.create_text_channel(f'Ticket {user}', category=category, overwrites=overwrites)
await channel.send(f"{user.mention}")
supem = discord.Embed(title=f"{user} Created a ticket.", description= "", color=0x00ff00)
supem.add_field(name="reason", value=f"``{reason}``")
supem.set_footer(text=f"staff will be with you shortly")
await channel.send(embed=supem)
Or, use category.create_text_channel instead.
#bot.command()
async def support(ctx, *, reason = None):
guild = ctx.guild
user = ctx.author
await ctx.message.delete() # Deletes the message of the author
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
# categories are just channels, so `get_channel` will get your category
category = await guild.get_channel(YOUR_CATEGORY_ID)
channel = await category.create_text_channel(f'Ticket {user}', overwrites=overwrites)
await channel.send(f"{user.mention}")
supem = discord.Embed(title=f"{user} Created a ticket.", description= "", color=0x00ff00)
supem.add_field(name="reason", value=f"``{reason}``")
supem.set_footer(text=f"staff will be with you shortly")
await channel.send(embed=supem)

Related

Creating private channels and deleting them in the discord

I want to make a system where when a user enters the private creation channel, a text channel and a voice channel are created, in the text the creator can give and take away the rights to enter the private, and if the owner leaves the private, then in a minute the channels should be deleted, as well as data about them from the database. I use MongoDB.
I have done almost all the code, but the code with the removal of channels does not work, namely, checking for the channel id. I also want to make sure that the timer for 30 is canceled if the creator returns, but there is some more convenient way to create this timer.
#bot.event
async def on_voice_state_update(member, before, after):
if after.channel is not None:
if after.channel.id == 992120556256247808:
guild = bot.get_guild(642681537284014080)
category = discord.utils.get(guild.categories, name='Приват')
v_channel = await guild.create_voice_channel(name=f'Приват ({member.display_name})', category=category)
t_channel = await guild.create_text_channel(name=f'Выдача прав ({member.display_name})', category=category)
await v_channel.set_permissions(member, connect=True, speak=True, view_channel=True, stream=True, kick_members=True, mute_members=True, priority_speaker=True)
role = discord.utils.get(guild.roles, id=642681537284014080)
await v_channel.set_permissions(role, view_channel=False)
await t_channel.set_permissions(role, view_channel=False)
private_post = {
'_id': member.id,
'text_id':t_channel.id,
'voice_id':v_channel.id,
}
private.insert_one(private_post)
await member.move_to(v_channel)
if before.channel == v_channel: #This one and the lines below it don't work
await bot.get_channel(private.find_one({'_id':member.id})['text_id']).send(f'`[PRIVATE]`: {member.mention}, Your private will be deleted in 1 minute!')
time.sleep(60000)
await t_channel.delete()
await v_channel.delete()
roles.delete_one({'_id': member.id})
#bot.command()
async def perm(ctx, member: discord.Member):
if ctx.channel.id == private.find_one({'text_id': ctx.channel.id})['text_id']:
v_channel = bot.get_channel(private.find_one({'text_id': ctx.channel.id})['voice_id'])
await v_channel.set_permissions(member, connect=True, speak=True, view_channel=True, stream=True)
#bot.command()
async def unperm(ctx, member: discord.Member):
if ctx.channel.id == private.find_one({'text_id': ctx.channel.id})['text_id']:
v_channel = bot.get_channel(private.find_one({'text_id': ctx.channel.id})['voice_id'])
await v_channel.set_permissions(member, connect=False, speak=False, view_channel=False, stream=False)
if member in v_channel.members:
await member.move_to(None)
you're using normal sleep in async code. use async sleep.
try using discord.ext.tasks to create timer. instead of sleep.
and the channel deletion. This should work :
#bot.event
async def on_voice_state_update(member, before, after):
if after.channel is not None:
if after.channel.id == 992120556256247808:
guild = bot.get_guild(642681537284014080)
category = discord.utils.get(guild.categories, name='Приват')
v_channel = await guild.create_voice_channel(name=f'Приват ({member.display_name})', category=category)
t_channel = await guild.create_text_channel(name=f'Выдача прав ({member.display_name})', category=category)
await v_channel.set_permissions(member, connect=True, speak=True, view_channel=True, stream=True, kick_members=True, mute_members=True, priority_speaker=True)
role = discord.utils.get(guild.roles, id=642681537284014080)
await v_channel.set_permissions(role, view_channel=False)
await t_channel.set_permissions(role, view_channel=False)
private_post = {
'_id': member.id,
'text_id': t_channel.id,
'voice_id': v_channel.id,
}
private.insert_one(private_post)
await member.move_to(v_channel)
if before.channel is not None:
channels = private.find_one({'_id':member.id})
t_channel = bot.get_channel(channels['text_id'])
v_channel = bot.get_channel(channels['voice_id'])
if before.channel.id != v_channel.id:
return
await t_channel.send(f'`[PRIVATE]`: {member.mention}, Your private will be deleted in 1 minute!')
await asyncio.sleep(60000)
await t_channel.delete()
await v_channel.delete()
roles.delete_one({'_id': member.id})

Discord.py "message" is not defined error even though nothing is wrong?

So I am pretty new to making Discord bots and python, however, whenever I try to run this it returns an error:
Here is my code:
import os
import discord
from discord.ext import commands
import keepAlive
keepAlive.awake("https://Shulker.E1ytra.repl.co", False)
TOKEN = os.environ['TOKEN']
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='?', intents=intents)
#bot.event
async def on_member_join(member):
guild = await bot.fetch_guild(958309214663622697)
role = discord.utils.get(guild.roles, name='unverified')
await member.add_roles(role)
await bot.process_commands(message)
#bot.command()
async def verf(ctx, arg):
if (arg == '51304'):
await ctx.message.delete()
member = ctx.author
role = discord.utils.get(ctx.guild.roles, name="Basement People")
await member.add_roles(role)
role = discord.utils.get(ctx.guild.roles, name="unverified")
await member.remove_roles(role)
embedVar = discord.Embed(title=" ", description=(ctx.message.author) + "Welcome to the server.", color=0x9b59b6)
await ctx.send(embed=embedVar, delete_after=5)
else:
await ctx.message.delete()
embedVar = discord.Embed(title=" ", description=(ctx.message.author) + "The secret code is invalid.", color=0x9b59b6)
await ctx.send(embed=embedVar, delete_after=5)
#bot.command()
#commands.has_permissions(kick_members=True)
async def kick(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "N/A"
await ctx.message.delete()
await ctx.guild.kick(member)
embedVar = discord.Embed(title=" ", description=f"{member.mention} has been kicked. Reason: {reason}", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "N/A"
await ctx.message.delete()
await ctx.guild.ban(member)
embedVar = discord.Embed(title=" ", description=f"{member.mention} has been banned. Reason: {reason}", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(ban_members=True)
async def unban(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "N/A"
await ctx.message.delete()
await ctx.guild.unban(member)
embedVar = discord.Embed(title=" ", description=f"{member.mention} has been unbanned. Reason: {reason}", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(manage_channels=True)
async def lock(ctx, channel : discord.TextChannel=None):
await ctx.message.delete()
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.send_messages = False
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title=" ", description=f"<#{ctx.channel.id}> has been locked.", color=0x9b59b6)
await ctx.send(embed=embedVar)
#bot.command()
#commands.has_permissions(manage_channels=True)
async def unlock(ctx, channel : discord.TextChannel=None):
await ctx.message.delete()
overwrite = ctx.channel.overwrites_for(ctx.guild.default_role)
overwrite.send_messages = True
await ctx.channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)
embedVar = discord.Embed(title=" ", description=f"<#{ctx.channel.id}> has been unlocked.", color=0x9b59b6)
await ctx.send(embed=embedVar)
bot.run(TOKEN)
It did run earlier and did perform actions without any errors but I don't know what's wrong in here. It's getting really confusing. I do not know what to assign to "message" to make it normal. Is this just Replit or something's wrong with my code?
Again, I am stupid, don't kill me in the comments.
When you do description=(ctx.message.author) + "Welcome to the server." python does not know how to get a string from the User (or Member) you get from the author field of message (docs).
What you probably want is ctx.message.author.mention which will give you a string that mentions the author or author.display_name.

I want to sort channels out under the category, how to move it? discord.py

I want to move the 2 newly created text and voice channels under the newly created category
#bot.command()
async def room(ctx, name):
guild = ctx.guild
member = ctx.author
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
}
channel = await guild.create_category_channel(name, overwrites=overwrites)
channel = await guild.create_text_channel(name, overwrites=overwrites)
channel = await guild.create_voice_channel(name, overwrites=overwrites)
channel = ctx.channel
name = discord.utils.get(ctx.guild.category, name)
await ctx.channel.edit(category=name)
Like this
How can I move two channels (chat, voice) below the category?
name = discord.utils.get(ctx.guild.category, name)
await ctx.channel.edit(category=name)
This code is not working
#bot.command()
async def room(ctx, roomname):
guild = ctx.guild
member = ctx.author
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
}
channel = await guild.create_category_channel(roomname, overwrites=overwrites)
text_channel = await guild.create_text_channel(roomname, category=channel, overwrites=overwrites)
voice_channel = await guild.create_voice_channel(roomname, category=channel, overwrites=overwrites)
I just entered the category=channel assignment in the channel parameter
then solved it.

I've been developing my reaction roles feature in discord.py, it's not working

I made a post about this yesterday and the code I was given didn't work, every time I try to run the command on a server that doesn't have the He/Him role, it gives me an error message saying that I have missing permissions
#bot.command(name='rolecreate', help='creates all the default roles')
#has_permissions(manage_messages=True, manage_roles=True)
async def rolecreate(ctx):
Text= "React with :heart: to get the He/Him role!"
Moji1 = await ctx.send(Text)
reaction="❤️"
await Moji1.add_reaction(reaction)
#bot.listen()
async def on_reaction_add(reaction, member):
if reaction.message.channel.id != 881380132789583892:
return
if reaction.emoji == "❤️":
he_him = discord.utils.get(member.guild.roles, name="He/Him")
if not he_him:
he_him = await member.guild.create_role(name="He/Him")
hello this is my reaction roles and it works great make sure to make the json file and stuff
import discord
from discord.ext import commands
import json
import atexit
import uuid
import datetime
x = datetime.datetime.now()
reaction_roles_data = {}
try:
with open("reaction_roles.json") as file:
reaction_roles_data = json.load(file)
except (FileNotFoundError, json.JSONDecodeError) as ex:
with open("reaction_roles.json", "w") as file:
json.dump({}, file)
#atexit.register
def store_reaction_roles():
with open("reaction_roles.json", "w") as file:
json.dump(reaction_roles_data, file)
class ReactionRoles(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_ready(self):
print(f"ReactionRoles ready.")
#commands.Cog.listener()
async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
role, user = self.parse_reaction_payload(payload)
if role is not None and user is not None:
await user.add_roles(role, reason="ReactionRole")
#commands.Cog.listener()
async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
role, user = self.parse_reaction_payload(payload)
if role is not None and user is not None:
await user.remove_roles(role, reason="ReactionRole")
#commands.has_permissions(manage_channels=True)
#commands.cooldown(1, 5, BucketType.user)
#commands.command()
async def reaction(
self,
ctx,
emote,
role: discord.Role,
channel: discord.TextChannel,
title,
message,
):
commandd = "reaction"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
embed = discord.Embed(title=title, description=message)
msg = await channel.send(embed=embed)
await msg.add_reaction(emote)
self.add_reaction(ctx.guild.id, emote, role.id, channel.id, msg.id)
#commands.has_permissions(manage_channels=True)
#commands.cooldown(1, 5, BucketType.user)
#commands.command()
async def reaction_add(
self, ctx, emote, role: discord.Role, channel: discord.TextChannel, message_id
):
commandd = "reaction_add"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
self.add_reaction(ctx.guild.id, emote, role.id, channel.id, message_id)
await ctx.send('Please enter the command like this: .reaction add (emote) (role (ping or id)) (channel (ping or id)) "(message title)" “(message)”')
#commands.has_permissions(manage_channels=True)
#commands.cooldown(1, 5, BucketType.user)
#commands.command()
async def reactions(self, ctx):
commandd = "reactions"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
guild_id = ctx.guild.id
data = reaction_roles_data.get(str(guild_id), None)
embed = discord.Embed(title="Reaction Roles")
if data is None:
embed.description = "There are no reaction roles set up right now."
else:
for index, rr in enumerate(data):
emote = rr.get("emote")
role_id = rr.get("roleID")
role = ctx.guild.get_role(role_id)
channel_id = rr.get("channelID")
message_id = rr.get("messageID")
embed.add_field(
name=index,
value=f"{emote} - #{role} - [message](https://www.discordapp.com/channels/{guild_id}/{channel_id}/{message_id})",
inline=False,
)
await ctx.send(embed=embed)
#commands.has_permissions(manage_channels=True)
#commands.cooldown(1, 5, BucketType.user)
#commands.command()
async def reaction_remove(self, ctx, index: int):
commandd = "reaction_remove"
print(f"{ctx.author.name}, {ctx.author.id} used command "+commandd+" used at ")
print(x)
print(" ")
guild_id = ctx.guild.id
data = reaction_roles_data.get(str(guild_id), None)
embed = discord.Embed(title=f"Remove Reaction Role {index}")
rr = None
if data is None:
embed.description = "Given Reaction Role was not found."
else:
embed.description = (
"Do you wish to remove the reaction role below? Please react with 🗑️."
)
rr = data[index]
emote = rr.get("emote")
role_id = rr.get("roleID")
role = ctx.guild.get_role(role_id)
channel_id = rr.get("channelID")
message_id = rr.get("messageID")
_id = rr.get("id")
embed.set_footer(text=_id)
embed.add_field(
name=index,
value=f"{emote} - #{role} - [message](https://www.discordapp.com/channels/{guild_id}/{channel_id}/{message_id})",
inline=False,
)
msg = await ctx.send(embed=embed)
if rr is not None:
await msg.add_reaction("🗑️")
def check(reaction, user):
return (
reaction.message.id == msg.id
and user == ctx.message.author
and str(reaction.emoji) == "🗑️"
)
reaction, user = await self.bot.wait_for("reaction_add", check=check)
data.remove(rr)
await ctx.send("removed reaction")
reaction_roles_data[str(guild_id)] = data
store_reaction_roles()
def add_reaction(self, guild_id, emote, role_id, channel_id, message_id):
if not str(guild_id) in reaction_roles_data and not message.author.bot:
reaction_roles_data[str(guild_id)] = []
reaction_roles_data[str(guild_id)].append(
{
"id": str(uuid.uuid4()),
"emote": emote,
"roleID": role_id,
"channelID": channel_id,
"messageID": message_id,
}
)
store_reaction_roles()
def parse_reaction_payload(self, payload: discord.RawReactionActionEvent):
guild_id = payload.guild_id
data = reaction_roles_data.get(str(guild_id), None)
if data is not None:
for rr in data:
emote = rr.get("emote")
if payload.message_id == rr.get("messageID"):
if payload.channel_id == rr.get("channelID"):
if str(payload.emoji) == emote:
guild = self.bot.get_guild(guild_id)
role = guild.get_role(rr.get("roleID"))
user = guild.get_member(payload.user_id)
return role, user
return None, None
def setup(bot):
bot.add_cog(ReactionRoles(bot))
-from head dev of rage bots

Adding member a ticket channel discord.py

I need help with the tickets. When someone wants to call for help everything is fine, creates a channel and a message but does not add the author of the command to the ticket channel and does not even see him. I hope you will help me!
#client.command()
async def support(ctx, *, reason = None):
guildid = ctx.guild.id
guild = ctx.guild
user = ctx.author
amount2 = 1
await ctx.channel.purge(limit=amount2)
channel = await guild.create_text_channel(f'Ticket {user}')
await channel.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
perms = channel.overwrites_for(user)
await channel.set_permissions(user, view_channel=not perms.view_channel)
await channel.set_permissions(user, read_message_history=not perms.read_message_history)
await channel.set_permissions(user, send_messages=not perms.send_messages)
await channel.send(f"{user.mention}")
supem = discord.Embed(title=f"{user} Poprosił o pomoc.", description= "", color=0x00ff00)
supem.add_field(name="Powód", value=f"``{reason}``")
supem.set_footer(text=f"Wkrótce przyjdzie do ciebie administrator ")
await channel.send(embed=supem)
You've wasted a lot of code on permissions there, it's much easier.
You can use discord.PermissionOverwrite here and then use it like this:
#client.command()
async def support(ctx, *, reason = None):
guild = ctx.guild
user = ctx.author
await ctx.message.delete() # Deletes the message of the author
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
user: discord.PermissionOverwrite(read_messages=True, send_messages=True)
}
channel = await guild.create_text_channel(f'Ticket {user}', overwrites=overwrites)
await channel.send(f"{user.mention}")
supem = discord.Embed(title=f"{user} Poprosił o pomoc.", description= "", color=0x00ff00)
supem.add_field(name="Powód", value=f"``{reason}``")
supem.set_footer(text=f"Wkrótce przyjdzie do ciebie administrator ")
await channel.send(embed=supem)
What did we do/how does the new code work?
guild.default_role: discord.PermissionOverwrite(read_messages=False) excludes the default role.
user: discord.PermissionOverwrite(read_messages=True, send_messages=True) the author, which you defined as user, has the permissions to read and write into the ticket.
We created a new text channel with the condition overwrites=overwrites.
I removed guildid = ctx.guild.id as you do not use it in your code.
Example 2 on the following site explains it also very well: Clik to re-direct

Categories