feat: complete

This commit is contained in:
Ting-Jun Wang 2024-08-23 02:52:02 +08:00
parent 6a549dacd4
commit 94363bc1ae
Signed by: snsd0805
GPG Key ID: 48D331A3D6160354
7 changed files with 214 additions and 12 deletions

1
accounts.json Normal file
View File

@ -0,0 +1 @@
{}

View File

@ -1,7 +0,0 @@
from discord.ext import commands
@commands.command()
async def ping(ctx: commands.Context, msg: str):
msg = f'{ctx.author} send message in {ctx.channel}: {ctx.command} {ctx.args}'
print(msg)
await ctx.send(msg)

18
main.py
View File

@ -1,12 +1,20 @@
import discord
from commands import *
from discord.ext import commands
import os
from src.cml_account import CMLAccountManager
import json
DISCORD_API_KEY = os.environ['DISCORD_API_KEY']
DB_USERNAME = 'web'
DB_PASSWORD = os.environ['DISCORD_BOT_DB_PASSWORD']
intents = discord.Intents.all()
client = commands.Bot(command_prefix='/', intents=intents)
cml_manager = CMLAccountManager(DB_USERNAME, DB_PASSWORD)
client.add_command(ping)
client.run(DISCORD_API_KEY)
if __name__ == '__main__':
intents = discord.Intents.all()
client = commands.Bot(command_prefix='/', intents=intents)
from src.commands import ping, bind
client.add_command(ping)
client.add_command(bind)
client.run(DISCORD_API_KEY)

28
src/cml_account.py Normal file
View File

@ -0,0 +1,28 @@
import mysql.connector
import os
class CMLAccountManager():
def __init__(self, db_username, db_password) -> None:
config = {
'user': db_username,
'password': db_password,
'host': 'cml4.csie.ntu.edu.tw', # 默認是 'localhost'
'database': 'CMLabWebSite',
'raise_on_warnings': True,
'ssl_disabled': True
}
self.conn = mysql.connector.connect(**config)
print("Connection successful")
def find_user(self, username):
cursor = self.conn.cursor()
query = "SELECT * FROM `People` WHERE `account`=%s"
param = (username, )
cursor.execute(query, param)
result = cursor.fetchone()
cursor.close()
return result

91
src/commands.py Normal file
View File

@ -0,0 +1,91 @@
from discord.ext import commands
from discord.utils import get
from main import cml_manager
from src.message import *
from src.dc_manage import *
import json
@commands.command()
async def ping(ctx: commands.Context, msg: str):
msg = f'{ctx.author} send message in {ctx.channel}: {ctx.command} {ctx.args}'
print(msg)
await ctx.send(msg)
@commands.command()
async def bind(ctx: commands.Context, username: str):
with open('accounts.json') as fp:
accounts = json.load(fp)
if username in accounts:
await ctx.send(BIND_BINDED.format(ctx.author.display_name, username))
return
# find user from CML database
user = cml_manager.find_user(username)
print(user)
if user == None:
await ctx.send(BIND_CANNOT_FIND_ACCOUNT.format(ctx.author.display_name, username))
return
# get user information
group = user[2].upper()
teacher = user[3]
first_name = user[8]
last_name = user[7]
# 確認 dc 名稱是不是正確
# 並且確認 CML 登陸的姓名是否跟 dc 一致
full_name = last_name + first_name
if f'-{full_name}' not in ctx.author.display_name:
await ctx.send(BIND_DIFFERENT_NAME.format(ctx.author.display_name, username))
return
uid = ctx.author.id
accounts[username] = {
'name': ctx.author.display_name,
'uid': uid
}
with open('accounts.json', 'w') as fp:
json.dump(accounts, fp, ensure_ascii=False)
'''
user = ctx.guild.get_member(uid)
await user.send("Hello, this is CML bot")
'''
# dc 分組
# 給 dc 身份組別
dc_group = None
if group == 'MIRA':
dc_group = 'R 組'
elif group == 'DSP':
dc_group = 'DSP 組'
elif group == 'GRAPHICS':
dc_group = 'G 組'
elif group == 'NETWORK':
dc_group = 'N 組'
elif group == 'AIMM':
dc_group = 'A 組'
elif group == 'SYSTEM':
dc_group = 'SYSTEM 組'
if dc_group != None:
# build group & add the user to the group
guild = ctx.guild
if not get(guild.roles, name=dc_group):
await create_group(guild, dc_group)
target_role = get(guild.roles, name=dc_group)
await ctx.author.add_roles(target_role)
msg = BIND_SUCCESS.format(first_name, group, dc_group, username)
else:
msg = BIND_GROUP_ERROR.format(first_name)
await ctx.send(msg)

39
src/dc_manage.py Normal file
View File

@ -0,0 +1,39 @@
import discord
async def create_group(guild: discord.Guild, name: str):
permissions = discord.Permissions.text()
permissions.add_reactions = True
permissions.stream = True
permissions.read_messages = True
permissions.send_messages = True
permissions.send_tts_messages = True
permissions.embed_links = True
permissions.attach_files = True
permissions.read_message_history = True
permissions.manage_messages = False
permissions.mention_everyone = True
permissions.external_emojis = True
permissions.connect = True
permissions.speak = True
permissions.use_voice_activation = True
permissions.change_nickname = True
permissions.manage_expressions = True
permissions.manage_emojis_and_stickers = True
permissions.use_application_commands = True
permissions.send_messages_in_threads = True
permissions.use_soundboard = True
permissions.send_voice_messages = True
permissions.send_polls = True
permissions.create_private_threads = False
permissions.create_public_threads = False
permissions.manage_threads = False
permissions.use_external_apps = True
permissions.create_instant_invite = True
await guild.create_role(
name=name,
hoist=True,
mentionable=True,
permissions=permissions
)

42
src/message.py Normal file
View File

@ -0,0 +1,42 @@
BIND_CANNOT_FIND_ACCOUNT = '''
Hi {},
我們無法在 CMLab 資料庫找到您輸入的帳號 (`{}`)
'''
BIND_DIFFERENT_NAME = '''
Hi {},
您似乎還沒有按照群組規則命名您的 Discord 名稱
or
資料庫紀錄 {} 的姓名與您目前的 Discord 並不相同:
> [學號前三碼]-[姓名] 例如: R13-王小明
如果修改過後仍然存在問題請找網管
您可以透過 DC 聯絡網管或 mail unix_manager@cmlab.csie.ntu.edu.tw
'''
BIND_SUCCESS = '''
Hi {},
我們從資料庫找到您屬於 `{} group`, 我們已經幫您分配到 Discord `{}` 的身份
並且已經綁定您的 CMLab 使用者帳號 `{}`未來若有實驗室相關通知我們能夠快速找到您
'''
BIND_GROUP_ERROR = '''
Hi {},
我們在幫您分組時出現了一點錯誤請聯絡網管
您可以透過 DC 聯絡網管或 mail unix_manager@cmlab.csie.ntu.edu.tw
'''
BIND_BINDED = '''
Hi {},
這個使用者帳號 `{}` 已經綁定過 Discord 帳號
您可以透過 DC 聯絡網管或 mail unix_manager@cmlab.csie.ntu.edu.tw
'''