python - 如何为用户生成随机 ID 并将其保存在文件中。在 Discord.py 中应该始终可以访问此 ID?
问题描述
我想出了用票务系统为我的服务器创建一个唯一 ID 系统的想法。它是这样工作的:当用户加入服务器时,机器人会自动生成 ID 并将此 ID 存储在一个文件中,该文件的用户 ID 来自 discord。如果用户使用机器人创建票证,机器人会将其为用户生成的 ID 添加到消息中。此外,应该有一个命令,允许我调用用户和他的 ID。
这是代码,我写的是生成随机ID
random = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)])
现在我想在票命令中访问它,如下所示:
@client.command(name='ticket-new')
async def create_channel(ctx, channel_name='unnamed_channel', *, reason=None):
member = ctx.author
guild = ctx.guild
existing_channel = discord.utils.get(guild.channels, name=channel_name)
reason_length = len(reason)
missing_length = 50 - reason_length
if reason_length < 50:
await ctx.send(f'Hey, your ticket should be at least 50 characters long to relay it to the moderators. {missing_length} missing characters.')
return
else:
if existing_channel:
await ctx.send(f'There is already a ticket with the name {channel_name}. Please selcet another name.')
if not existing_channel:
channel = await guild.create_text_channel(channel_name)
await channel.set_permissions(guild.default_role, read_messages=False)
await channel.set_permissions(ctx.author, read_messages=True)
embed = discord.Embed(title=f"Ticket: {channel_name}", description=f"**Description**: {reason}\n**ID**: {random}")
await channel.send(embed=embed)
await member.send("Ticket: `" + channel_name + '` erstellt!')
print(f'Creating a new ticket channel: {channel_name}, by {member.name}, at {ctx.message.created_at}, on: {guild.name}, ID: {random}')
嗯......我现在的计划是将用户随机存储在一个文件中。另外......也许如何通过命令访问信息。
解决方案
我会用 SQL
来实现代码的工作,你需要:
1. 下载 SQLite Studio - https://sqlitestudio.pl/
2. 在 SQLite Studio 中创建新的数据库文件,与你的不和谐机器人代码
代码相同:
import sqlite3
db = sqlite3.connect('database_file_name.db')
cursor = db.cursor()
async def addUserID(user):
serverID = user.guild.id
id = 0
# if user already have id in database the code will break
try:
if cursor.execute("SELECT * FROM `{0}` WHERE `discord_id` = '{1}'".format(serverID, user.id)): return
except: pass
try:
# if table for this server was already created
for i in cursor.execute('SELECT COUNT(`id`) FROM `{}`'.format(str(serverID))): id = i[0]
cursor.execute("INSERT INTO `{0}` (`user`, `discord_id`, `id`) VALUES('{1}', '{2}', '{3}')".format(serverID, user, str(user.id), id))
except:
# otherwise, it creates a table for this server and puts the user data there
cursor.execute('CREATE TABLE `{}` ( `user` VARCHAR(255) NOT NULL , `discord_id` INT NOT NULL , `id` INT NOT NULL )'.format(serverID))
for i in cursor.execute('SELECT COUNT(`id`) FROM `{}`'.format(serverID)): id = i[0]
cursor.execute("INSERT INTO `{0}` (`user`, `discord_id`, `id`) VALUES('{1}', '{2}', '{3}')".format(serverID, user, str(user.id), id))
# this function returns the id you wanted to implement, but before using this function you must use the addUserID() function
async def getUserID(user):
try:
for row in cursor.execute("SELECT * FROM `{0}` WHERE `discord_id` = '{1}'".format(user.guild.id, user.id)): return row[2]
except Exception as error:
raise Exception('The user has no identifier. To add an ID to a user, use the addUserID(discord.Member) function\n\nError:\n' + str(error))
# when member joined it is adding to this member id and prints it
@bot.event
async def on_member_join(member):
await addUserID(member)
print('Own user id: ' + await getUserID(member))
对不起我的英语不好
推荐阅读
- xampp - 无法在 XAMPP 中编辑 config.inc.php
- flutter - 如何在 Flutter 中设计过滤器?
- python - exec() python 命令停止整个执行
- apache-kafka-connect - 没有任何日志文件包含偏移 SCN: 9483418337736,需要重新快照
- kubeflow - 如何以编程方式从管道函数创建 Kubeflow 循环运行?
- c++ - Arduino millis() 一个接一个地打印值
- python - 如何将多维数组存储在python的文件中?
- javascript - 无法使用 Socket.io 连接到 WebSocket | WS
- reactjs - 使用 nodemailer 发送电子邮件收到错误“ERR_INVALID_ARG_TYPE”
- reactjs - React Hooks:来自 useCallback 的自定义钩子