From 6062167a6525ab419a38107abaf87a256e89537f Mon Sep 17 00:00:00 2001 From: lonnstyle <54892447+lonnstyle@users.noreply.github.com> Date: Tue, 23 Mar 2021 15:58:42 +0800 Subject: [PATCH] v2.1.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 將所有輸出界面改為從json導入str --- cmds/admin.py | 10 ++- cmds/baro.py | 30 ++++--- cmds/common.py | 117 ++++++++++--------------- cmds/event.py | 55 ++++++++++-- cmds/logup.py | 13 ++- cmds/rivenPrice.py | 64 ++++++++------ cmds/wfm.py | 111 ++++++++++++++---------- cmds/wiki.py | 30 ++++--- cmds/worldState.py | 61 ++++++------- language.py | 14 +++ main.py | 90 ++++++++++--------- setting.json | 13 +-- zh-hant.json | 210 +++++++++++++++++++++++++++++++++++++++++++++ 13 files changed, 570 insertions(+), 248 deletions(-) create mode 100644 language.py create mode 100644 zh-hant.json diff --git a/cmds/admin.py b/cmds/admin.py index db57b8d..919e4ef 100644 --- a/cmds/admin.py +++ b/cmds/admin.py @@ -3,6 +3,10 @@ from core.classes import Cog_Extension import os import json +from language import language as lang + +lang = lang() +lang = lang.langpref()['admin'] with open('setting.json', 'r', encoding='utf8') as jfile: jdata = json.load(jfile) @@ -11,13 +15,13 @@ class admin(Cog_Extension): tag = "admin" #清除訊息 - @commands.command(name='clear', aliases=['clean' , '清除'],brief="刪除聊天記錄",description="clear [指定數量]\n刪除指定數量的聊天記錄") + @commands.command(name='clear', aliases=lang['clear.aliases'],brief=lang['clear.brief'],description=lang['clear.description']) async def clear(self,ctx,num:int): if ctx.message.author.id == ctx.guild.owner_id: await ctx.channel.purge(limit=num+1) - print(str(ctx.message.author)+' ---ID '+str(ctx.message.author.id)+'在 << '+str(ctx.channel.name)+' >> 頻道使用了clear指令刪除了'+str(int(num))+'個對話') + print(str(ctx.message.author)+' ---ID '+str(ctx.message.author.id)+lang['clear.cleared'].format(channel=str(ctx.channel.name),num=str(int(num)))) else: - embed = discord.embed(title="權限不足",description='本指令只提供給伺服器傭有者 \n本伺服器擁有者為 <@' + str(ctx.guild.owner_id) + '>') + embed = discord.embed(title=lang['clear.error.title'],description=lang['clear.error.description'].format(owner=self.bot.owner_id)) await ctx.send(embed=embed) def setup(bot): diff --git a/cmds/baro.py b/cmds/baro.py index 0698d62..d414e7b 100644 --- a/cmds/baro.py +++ b/cmds/baro.py @@ -6,14 +6,18 @@ import json import asyncio import chinese_converter +from language import language as lang -rawDict = requests.get("https://raw.githubusercontent.com/lonnstyle/riven-mirror/dev/src/i18n/lang/zh-Hant.json") +lang = lang() +lang = lang.langpref()['baro'] + +rawDict = requests.get(lang['rawDict.URL']) Dict = json.loads(rawDict.text) Dict = Dict['messages'] class baro(Cog_Extension): tag = "Warframe" - @commands.command(name='baro',aliases=['奸商' , 'Baro'],brief="虛空商人信息",description="查詢虛空商人Baro Ki'Teer目前狀態\t如已經抵達中繼站則會顯示所攜帶商品列表") + @commands.command(name='baro',aliases=lang['baro.aliases'],brief=lang['baro.brief'],description=lang['baro.description']) async def baroManual(self,ctx): url = requests.get("https://api.warframestat.us/pc/tc/voidTrader",headers={'Accept-Language':'zh','Cache-Control': 'no-cache'}) html = json.loads(url.text) @@ -22,10 +26,10 @@ async def baroManual(self,ctx): location = html['location'] location = chinese_converter.to_traditional(location) stay = html['endString'] - stay = stay.replace("d","天") - stay = stay.replace("h","小時") - stay = stay.replace("m","分鐘") - stay = stay.replace("s","秒") + stay = stay.replace("d",lang['baro.time.day']) + stay = stay.replace("h",lang['baro.time.hour']) + stay = stay.replace("m",lang['baro.time.minute']) + stay = stay.replace("s",lang['baro.time.second']) for items in html['inventory']: item = items['item'] item = item.lower() @@ -42,19 +46,19 @@ async def baroManual(self,ctx): name = Dict.get(name,name) ducats = items['ducats'] credits = items['credits'] - message += f"物品:{name}\n杜卡德金幣:{ducats}\t現金:{credits}\n" + message += lang['baro.item'].format(name=name,ducats=ducats,credits=credits) message += "```" - embed = discord.Embed(title=f"Baro Ki'Teer 已經到達{location},停留時間為{stay}\t帶來的商品如下:",description=message,color=0x429990) + embed = discord.Embed(title=lang['baro.arrived'].format(location=location,stay=stay),description=message,color=0x429990) await ctx.send(embed=embed) if html['active'] == False: location = html['location'] location = chinese_converter.to_traditional(location) arrive = html['startString'] - arrive = arrive.replace("d","天") - arrive = arrive.replace("h","小時") - arrive = arrive.replace("m","分鐘") - arrive = arrive.replace("s","秒") - embed = discord.Embed(description=f"Baro Ki' Teer會在{arrive}後抵達{location}",color=0x429990) + arrive = arrive.replace("d",lang['baro.time.day']) + arrive = arrive.replace("h",lang['baro.time.hour']) + arrive = arrive.replace("m",lang['baro.time.minute']) + arrive = arrive.replace("s",lang['baro.time.second']) + embed = discord.Embed(description=lang['baro.arrival'].format(arrive=arrive,location=location),color=0x429990) await ctx.send(embed=embed) diff --git a/cmds/common.py b/cmds/common.py index 3848a8e..3430c4f 100644 --- a/cmds/common.py +++ b/cmds/common.py @@ -1,86 +1,63 @@ import discord from discord.ext import commands -from core.classes import Cog_Extension +from core.classes import Cog_Extension import random -import json -from random import randint -import requests +import json +from random import randint +import requests import re -import asyncio - +import asyncio +from language import language as lang + +lang = lang() +lang = lang.langpref()['common'] with open('setting.json', 'r', encoding='utf8') as jfile: jdata = json.load(jfile) + +emoji = requests.get("http://gist.githubusercontent.com/Vexs/629488c4bb4126ad2a9909309ed6bd71/raw/416403f7080d1b353d8517dfef5acec9aafda6c3/emoji_map.json").text +emoji = json.loads(emoji) +emoji = {x: y for y, x in emoji.items()} -emoji = requests.get("http://gist.githubusercontent.com/Vexs/629488c4bb4126ad2a9909309ed6bd71/raw/416403f7080d1b353d8517dfef5acec9aafda6c3/emoji_map.json").text -emoji = json.loads(emoji) -emoji = {x: y for y, x in emoji.items()} - -class common(Cog_Extension): +class common(Cog_Extension): tag = "common" #ping - @commands.command(name= 'ping', aliases=['延遲' , '機器人延遲' , 'delay'],brief="測試延遲",description="顯示當前機器人處理信息的延遲值") - async def ping(self, ctx): - latency = round(self.bot.latency*1000) - red = max(0,min(int(255*(latency-50)/1000),255)) - green = 255-red - color = discord.Colour.from_rgb(r=red,g=green,b=0) - embed = discord.Embed(title="當前本機延遲為",description=f'{latency} 毫秒 (ms)',color=color) - await ctx.send(embed=embed) + @commands.command(name= 'ping', aliases=lang['ping.aliases'],brief=lang['ping.brief'],description=lang['ping.description']) + async def ping(self, ctx): + latency = round(self.bot.latency*1000) + red = max(0,min(int(255*(latency-50)/1000),255)) + green = 255-red + color = discord.Colour.from_rgb(r=red,g=green,b=0) + embed = discord.Embed(title=lang['ping.embed.title'],description=lang['ping.latency'].format(latency=latency),color=color) + await ctx.send(embed=embed) #說 - @commands.command(name= 'sayd', aliases=['說' , '機器人說'],brief="復讀",description="讓機器人代替你說出`msg`的內容") + @commands.command(name= 'sayd', aliases=lang['sayd.aliases'],brief=lang['sayd.brief'],description=lang['sayd.description']) async def sayd(self,ctx,*,msg): await ctx.message.delete() - embed=discord.Embed(description=msg,color=0x3C879C) - message = await ctx.send(embed=embed) - #此功能為開發伺服器上公告自動廣播之用 - if ctx.channel.id == 820571680479903776: - await message.publish() - - @commands.command(name= 'poll', aliases=['投票'],brief="發起投票",description="讓機器人發起一項投票") - async def poll(self,ctx,topic,option1,emoji1,option2,emoji2): - await ctx.message.delete() - match1 = re.match(r'<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$', emoji1) - match2 = re.match(r'<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$', emoji2) - if (emoji.get(emoji1,None)!=None or match1) and (emoji.get(emoji2,None)!=None or match2): - if emoji1 == emoji2 or option1 == option2: - await ctx.send(embed=discord.Embed(title="錯誤信息",description='兩個一樣你要投什麼?',color=0xff0000)) - return - embed=discord.Embed(description=topic,color=0x3C879C) - embed.add_field(name=option1,value=emoji1) - embed.add_field(name=option2,value=emoji2) - message = await ctx.send(embed=embed) - await message.add_reaction(emoji1) - await message.add_reaction(emoji2) - else: - await ctx.send(embed=discord.Embed(title="錯誤信息",description='這真的是emoji嗎?')) - - @commands.command(name="role",brief="新增身份組",description="新增機器人可以分發的身份組") - async def role(self,ctx,role): - if ctx.message.author.id == ctx.guild.owner_id: - for roles in ctx.guild.roles: - if roles.name == role: - embed = discord.Embed(title="已新增身份組",description=f"已新增<@&{roles.id}>") - await ctx.send(embed=embed) - with open("roles.txt","a",encoding="utf8") as role_id: - role_id.write(roles.name+'\n') - - @commands.command(name="join",brief="加入身份組",description="使機器人分配身份組權限") - async def join(self,ctx,role): - await ctx.message.delete() - with open("roles.txt","r",encoding="utf8") as roles: - if (role+'\n') in roles.readlines(): - for roles in ctx.guild.roles: - if roles.name == role: - await ctx.author.add_roles(roles) - message = await ctx.send(embed=discord.Embed(title="已加入身份組",description=f"<@&{roles.id}>",color=0x00ff00)) - await asyncio.sleep(10) - message.delete() - else: - message = await ctx.send(embed=discord.Embed(title="加入身份組失敗",description="請確保身份組輸入無誤",color=0xff0000)) - await asyncio.sleep(10) - message.delete() + embed=discord.Embed(description=msg,color=0x3C879C) + message = await ctx.send(embed=embed) + if ctx.channel.id == jdata['publish']: + await message.publish() + + @commands.command(name= 'poll', aliases=lang['poll.aliases'],brief=lang['poll.brief'],description=lang['poll.description']) + async def poll(self,ctx,topic,option1,emoji1,option2,emoji2): + await ctx.message.delete() + match1 = re.match(r'<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$', emoji1) + match2 = re.match(r'<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$', emoji2) + if (emoji.get(emoji1,None)!=None or match1) and (emoji.get(emoji2,None)!=None or match2): + if emoji1 == emoji2 or option1 == option2: + await ctx.send(embed=discord.Embed(title=lang['poll.error.title'],description=lang['poll.error.description.same'],color=0xff0000)) + return + embed=discord.Embed(description=topic,color=0x3C879C) + embed.add_field(name=option1,value=emoji1) + embed.add_field(name=option2,value=emoji2) + message = await ctx.send(embed=embed) + await message.add_reaction(emoji1) + await message.add_reaction(emoji2) + else: + await ctx.send(embed=discord.Embed(title=lang['poll.error.title'],description=lang['poll.error.description.emoji'])) + def setup(bot): - bot.add_cog(common(bot)) + bot.add_cog(common(bot)) \ No newline at end of file diff --git a/cmds/event.py b/cmds/event.py index e0008f6..e5b8f17 100644 --- a/cmds/event.py +++ b/cmds/event.py @@ -4,33 +4,78 @@ from datetime import datetime,timedelta import json import os +import requests +import re +import discord +from language import language as lang + +lang = lang() +lang = lang.langpref()['event'] with open('setting.json', 'r', encoding='utf8') as jfile: jdata = json.load(jfile) +emojimap = requests.get("http://gist.githubusercontent.com/Vexs/629488c4bb4126ad2a9909309ed6bd71/raw/416403f7080d1b353d8517dfef5acec9aafda6c3/emoji_map.json").text +emojimap = json.loads(emojimap) +emojimap = {x: y for y, x in emojimap.items()} class event(Cog_Extension): tag = "common" + @commands.command(name="reactionRole", aliases=["rr"],brief="指定自動身份組訊息",description="指定可自動分發身份組的訊息") + async def rr(self,ctx,message:int): + with open("role/rr.txt","a") as rr: + rr.write(f"{message}\n") + await ctx.message.add_reaction("✅") + await ctx.message.delete(delay=5) + + + @commands.command(name='role', aliases=lang['role.aliases'],brief=lang['role.brief'],description=lang['role.description']) + async def role(self,ctx,role:str,emoji): + match = re.match(r'<(a?):([a-zA-Z0-9\_]+):([0-9]+)>$', emoji) + if (emojimap.get(emoji,None)!=None or match) and ctx.author.guild_permissions.administrator == True: + with open("role/roles.txt","a") as roles: + roles.write(f"{emoji},{role}\n") + await ctx.message.add_reaction("✅") + await ctx.message.delete(delay=5) + else: + await ctx.message.delete() + await ctx.send(embed=discord.Embed(title=lang['role.error.title'],description=lang['role.error.description'])) + + @commands.Cog.listener() + async def on_raw_reaction_add(self,payload): + roles = {} + message = [] + raw = open("role/roles.txt","r") + rr = open("role/rr.txt","r") + for line in raw.readlines(): + emoji,role = line.split(",") + roles[emoji] = role.replace("\n","") + for line in rr.readlines(): + message.append(line.replace("\n","")) + for role in payload.member.guild.roles: + if (role.name == roles.get(payload.emoji.name) or role.name == roles.get(f"<:{payload.emoji.name}:{payload.emoji.id}>")) and str(payload.message_id) in message: + await payload.member.add_roles(role) + @commands.Cog.listener() async def on_message(self,msg): if str(msg.channel.type) == 'private' and msg.author != self.bot.user: - print(time_info.UTC_8() + str(msg.author) + '說:' + msg.content) + print(time_info.UTC_8() + str(msg.author) + lang['onMessage.say'] + msg.content) fp = open('./log/' + 'Private.log', 'a',encoding='utf8') - fp.write(time_info.UTC_8() + str(msg.author) + '說:' + msg.content+'\n') + fp.write(time_info.UTC_8() + str(msg.author) + lang['onMessage.say'] + msg.content+'\n') fp.close() else: if str(msg.channel.type) == 'text' and msg.author != self.bot.user: - print(time_info.UTC_8_CH() + str(msg.author) + '說:' + msg.content) + print(time_info.UTC_8_CH() + str(msg.author) + lang['onMessage.say'] + msg.content) for items in msg.attachments: print(items) a = str(msg.guild) b = str(msg.channel) fp = open('./log/' + a + '-' + b + '.log', 'a',encoding='utf8') - fp.write(time_info.UTC_8() + str(msg.author) + '說:' + msg.content+'\n') + fp.write(time_info.UTC_8() + str(msg.author) + lang['onMessage.say'] + msg.content+'\n') fp.close() pass def setup(bot): if not os.path.exists('log'): os.mkdir('log') - bot.add_cog(event(bot)) + bot.add_cog(event(bot)) \ No newline at end of file diff --git a/cmds/logup.py b/cmds/logup.py index f8bd254..72c74ba 100644 --- a/cmds/logup.py +++ b/cmds/logup.py @@ -3,6 +3,11 @@ from core.classes import Cog_Extension import os import json +from language import language as lang + +lang = lang() +lang = lang.langpref()['event'] + with open('setting.json','r',encoding='utf8') as jset: jdata = json.load(jset) @@ -19,7 +24,7 @@ class logup(Cog_Extension): tag = "common" @commands.command() async def loglist(self,ctx): - if str(ctx.author.id) == jdata['owner']: + if await self.bot.is_owner(ctx.message.author): msg = '' dou = 0 for i in loglist: @@ -34,7 +39,7 @@ async def loglist(self,ctx): @commands.command() async def reloadlog(self,ctx): - if str(ctx.author.id) == jdata['owner']: + if await self.bot.is_owner(ctx.message.author): global loglist,logindex loglist = [] for logname in os.listdir('./log'): @@ -42,12 +47,12 @@ async def reloadlog(self,ctx): loglist.append(logindex) loglist.append(logname) logindex += 1 - await ctx.send('已重新加載') + await ctx.send(lang['reloadlog.reloaded']) logindex = 0 @commands.command() async def downloadlog(self,ctx,index): - if str(ctx.author.id) == jdata['owner']: + if await self.bot.is_owner(ctx.message.author): for i in loglist: if i == int(index): a = 'log\\'+loglist[i+1] diff --git a/cmds/rivenPrice.py b/cmds/rivenPrice.py index df7e72b..52e2357 100644 --- a/cmds/rivenPrice.py +++ b/cmds/rivenPrice.py @@ -5,10 +5,23 @@ import requests import json from discord_webhook import DiscordWebhook,DiscordEmbed +from language import language as lang -weapons = json.loads(requests.get("https://raw.githubusercontent.com/lonnstyle/DiscordBotMods/main/dict/Weapons.json").text) -weapons = {x: y for y, x in weapons.items()} -attrDict = json.loads(requests.get("https://raw.githubusercontent.com/lonnstyle/DiscordBotExt/main/dict/attributes.json").text) +lang = lang() +lang = lang.langpref()['rivenPrice'] + +temp = {} +weapons = json.loads(requests.get("http://api.warframe.market/v1/riven/items",headers=lang['api.header']).text) +weapons = weapons['payload']['items'] +for item in weapons: + temp[item['item_name']]=item['url_name'] +weapons = temp +temp = {} +attrDict = json.loads(requests.get("http://api.warframe.market/v1/riven/attributes",headers=lang['api.header']).text) +attrDict = attrDict['payload']['attributes'] +for attr in attrDict: + temp[attr['url_name']]=attr['effect'] +attrDict=temp with open('setting.json', 'r', encoding='utf8') as jfile: jdata = json.load(jfile) @@ -16,10 +29,10 @@ class rivenPrice(Cog_Extension): tag = "Warframe" - @commands.command(name='riven',aliases=['紫卡','紫卡查詢'],brief="查詢裂罅價格",description="查詢`weapon`裂罅價格") + @commands.command(name='riven',aliases=lang['riven.aliases'],brief=lang['riven.brief'],description=lang['riven.description']) async def rivenPrice(self,ctx,*weapon): name = ' '.join(weapon) - Chinese= name + userInput= name weapon = weapons.get(name, "Empty") if weapon == "Empty": weapon = name @@ -28,7 +41,7 @@ async def rivenPrice(self,ctx,*weapon): html = requests.get(url) weapon = weapon.replace("_"," ") if html.status_code != 200: - await ctx.send(embed=discord.Embed(title="出錯啦!",description='查到...Ordis發生錯誤...API出錯!',color=0xff0000)) + await ctx.send(embed=discord.Embed(title=lang['riven.error.title'],description=lang['riven.error.description'],color=0xff0000)) print(weapon) return() else: @@ -44,7 +57,7 @@ async def rivenPrice(self,ctx,*weapon): webhookID = requests.get(webhookID) webhookID = json.loads(webhookID.text) webhookID = webhookID['channel_id'] - message = f'以下為{Chinese}紫卡的查詢結果(按價格由低至高順序)\n' + message = lang['riven.message.title'].format(userInput=userInput) webhook = DiscordWebhook(url=jdata['webhook'],content=message) for items in rivenData: if count < 3: @@ -52,32 +65,33 @@ async def rivenPrice(self,ctx,*weapon): if owner['status'] != 'offline': rivenItem = items['item'] rivenName = rivenItem['name'] - message += f'```\n紫卡名稱:{Chinese} {rivenName}\n' + message += lang['riven.message.rivenName'].format(userInput=userInput,rivenName=rivenName) ownerName = owner['ingame_name'] avatar = owner['avatar'] if avatar == None: avatar = "user/default-avatar.png" - message += f'賣家:{ownerName}\n' + message += lang['riven.message.owner'].format(ownerName=ownerName) rank = rivenItem['mod_rank'] rerolls = rivenItem['re_rolls'] - message += f'等級:{rank}\n' - message += f'迴圈次數:{rerolls}\n' - embed = DiscordEmbed(title=f"紫卡名稱:{Chinese} {rivenName}",description=f'等級:{rank} 迴圈次數:{rerolls}',color=0xb59dd4) - embed.set_author(name=ownerName, icon_url="https://warframe.market/static/assets/"+avatar, url = "https://warframe.market/zh-hant/profile/"+ownerName) + message += lang['riven.message.rank'].format(rank=rank) + message += lang['riven.message.reroll'].format(rerolls=rerolls) + embed = DiscordEmbed(title=lang['riven.embed.title'].format(userInput=userInput,rivenName=rivenName),description=lang['riven.embed.description'].format(rank=rank,rerolls=rerolls),color=0xb59dd4) + embed.set_author(name=ownerName, icon_url="https://warframe.market/static/assets/"+avatar, url = f"https://warframe.market/{lang['riven.link.language']}/profile/"+ownerName) if items['top_bid'] == 'None': top_bid = items['top_bid'] - message += f'目前競標:{top_bid}\n' - embed.add_embed_field(name="目前競標:",value=top_bid) + message += lang['riven.message.topbid'].format(top_bid=top_bid) + embed.add_embed_field(name=lang['riven.embed.field.topbid'],value=top_bid) else: starting_price = items['starting_price'] buyout_price = items['buyout_price'] if starting_price == buyout_price: - message += f'價格:{buyout_price}\n' - embed.add_embed_field(name="價格:",value=buyout_price) + message += lang['riven.message.price'].format(buyout_price=buyout_price) + embed.add_embed_field(name=lang['riven.embed.field.price'],value=buyout_price) else: - message += f'起標價格:{starting_price}\n' - message += f'買斷價格:{buyout_price}\n' - embed.add_embed_field(name="價格:",value=buyout_price,inline=False) + message += lang['riven.message.starting'].format(starting_price=starting_price) + message += lang['riven.message.buyout'].format(buyout_price=buyout_price) + embed.add_embed_field(name=lang['riven.embed.field.starting'],value=starting_price,inline=False) + embed.add_embed_field(name=lang['riven.embed.field.buyout'],value=buyout_price,inline=False) positive = '' negative = '' for attr in rivenItem['attributes']: @@ -85,14 +99,14 @@ async def rivenPrice(self,ctx,*weapon): attribute = attrDict.get(attribute,attribute) value = attr['value'] if attr['positive'] == True: - message += f'正面詞條:{attribute} {value}\n' + message += lang['riven.message.attr.pos'].format(attribute=attribute,value=value) positive += f'{attribute} {value}\n' elif attr['positive'] == False: - message += f'負面詞條:{attribute} {value}\n' + message += lang['riven.message.attr.neg'].format(attribute=attribute,value=value) negative = f'{attribute} {value}' - embed.add_embed_field(name="正面詞條:",value=positive[:-1]) + embed.add_embed_field(name=lang['riven.embed.attr.pos'],value=positive[:-1]) if negative != '': - embed.add_embed_field(name="負面詞條:",value=negative) + embed.add_embed_field(name=lang['riven.embed.attr.neg'],value=negative) count += 1 message += '```' webhook.add_embed(embed) @@ -103,4 +117,4 @@ async def rivenPrice(self,ctx,*weapon): def setup(bot): - bot.add_cog(rivenPrice(bot)) + bot.add_cog(rivenPrice(bot)) \ No newline at end of file diff --git a/cmds/wfm.py b/cmds/wfm.py index e3ee679..b1135a0 100644 --- a/cmds/wfm.py +++ b/cmds/wfm.py @@ -4,51 +4,66 @@ import json import discord from discord_webhook import DiscordWebhook, DiscordEmbed +from language import language as lang + +lang = lang() +lang = lang.langpref()['wfm'] + with open('setting.json', 'r', encoding='utf8') as jfile: jdata = json.load(jfile) -zhDict = requests.get("https://raw.githubusercontent.com/lonnstyle/DiscordBotMods/main/dict/items_zh-hant.json") -zhDict = json.loads(zhDict.text) -zhDictRev = zhDict -zhDict = {x: y for y, x in zhDict.items()} -enDict = requests.get("https://raw.githubusercontent.com/lonnstyle/DiscordBotMods/main/dict/items_en.json") +localDict = requests.get("http://api.warframe.market/v1/items",headers=lang['api.header']) +localDict = json.loads(localDict.text) +temp = {} +localDict = localDict['payload']['items'] +for item in localDict: + temp[item['item_name']] = item['url_name'] +localDict=temp +enDict = requests.get("http://api.warframe.market/v1/items") enDict = json.loads(enDict.text) +temp = {} +enDict = enDict['payload']['items'] +for item in enDict: + temp[item['item_name']] = item['url_name'] +enDict=temp +localDictRev = localDict enDictRev = enDict -enDict = {x: y for y, x in enDict.items()} -Chinese_order_type = {'buy':'買','sell':'賣'} +localDictRev = {x: y for y, x in localDictRev.items()} +enDictRev = {x: y for y, x in enDictRev.items()} +local_order_type = lang['local_order_type'] +price_order = lang['price_order'] class wfm(Cog_Extension): tag = "Warframe" - @commands.command(name='translate',aliases=['trans','翻譯'],brief="進行中英文翻譯",description="翻譯`item`於[wf.m](https://warframe.market)上的名稱") + @commands.command(name='translate',aliases=lang['translate.aliases'],brief=lang['translate.brief'],description=lang['translate.description']) async def translate(self,ctx,*item): - item = ' '.join(item) + item = ' '.join(word.capitalize() for word in(item.split())) url_name = enDict.get(item,item) language = '' if url_name == item: - url_name = zhDict.get(item,item) + url_name = localDict.get(item,item) if url_name == item: - message = "Ordis沒找到指揮官說的物品呢" + message = lang['translate.error.notFound'].format(self=jdata['self'],user=jdata['user']) await ctx.send(message) return else: translate = enDictRev[url_name] - language = "英文" - print(translate+url_name) + language = lang['translate.language.en'] else: - translate = zhDictRev.get(url_name,item) + translate = localDictRev.get(url_name,item) if translate == item: - message = "Ordis也不太清楚翻譯是什麼呢" + message = lang['translate.error.noTrans'].format(self=jdata['self']) await ctx.send(message) return else: - language = "中文" - message = f"`{item}` 的{language}翻譯為 `{translate}`" + language = lang['translate.language.local'] + message = lang['translate.translate.message'].format(item=item,language=language,translate=translate) await ctx.send(message) - @commands.command(name='wfm', aliases=['wm', '市場查詢'],brief="查詢物品價格",description="查詢`item`於[wf.m](https://warframe.market)上的價格") - async def market(self, ctx, *item): + @commands.command(name='wfm', aliases=lang['wfm.aliases'],brief=lang['wfm.brief'],description=lang['wfm.description']) + async def market(self, ctx, *args): if str(ctx.channel.type) != 'private': channel_id = ctx.channel.id else: @@ -56,14 +71,14 @@ async def market(self, ctx, *item): action = 'buy' order_type = 'sell' itemrank = None - args = ' '.join(item) + args = ' '.join(args) if args.count(',')==0: items = args elif args.count(',')==1: - if '買,'in args: - args = args.replace('買,','') - elif '賣,' in args: - args = args.replace('賣,','') + if (lang['wfm.buy']+',') in args: + args = args.replace((lang['wfm.buy']+','),'') + elif (lang['wfm.sell']+',') in args: + args = args.replace((lang['wfm.sell']+','),'') action = 'sell' order_type = 'buy' else: @@ -72,24 +87,25 @@ async def market(self, ctx, *item): items = args elif args.count(',')==2: order_type,items,itemrank = args.split(',') - if order_type == '買': + if order_type == lang['wfm.buy']: order_type = 'sell' - elif order_type == '賣': + elif order_type == lang['wfm.sell']: order_type = 'buy' action = 'sell' else: - await ctx.send('指揮官是要買還是賣呢?') + await ctx.send(lang['wfm.error.unknownOrder'].format(user=jdata['user'])) else: - await ctx.send("指揮官說的太多了,Ordis不是很懂呢") + await ctx.send(lang['wfm.error.tooManyArgs'].format(user=jdata['user'],self=jdata['self'])) count = 5 - item = zhDict.get(items, items) + items= ' '.join(word.capitalize() for word in(items.split())) + item = localDict.get(items, items) if item == items: item = enDict.get(items,items) if item == items: item=item.replace(" ","_").lower() try: itemsDetail = json.loads(requests.get("https://api.warframe.market/v1/items/" + item).text.encode(encoding="UTF-8"))["payload"]["item"]["items_in_set"] except: - await ctx.send("Ordis不太清楚指揮官說的什麼呢") + await ctx.send(lang["wfm.error.unknownItem"].format(self=jdata['self'])) return max_rank = None for itemDetail in itemsDetail: @@ -98,12 +114,12 @@ async def market(self, ctx, *item): max_rank = int(itemDetail["mod_max_rank"]) itemrank = int(itemrank) if itemrank > max_rank: - await ctx.send("指揮官所輸入的等級超出物品最高等級呢 0.0") + await ctx.send(lang["wfm.error.outOfRank"].format(user=jdata['user'])) return url = "https://api.warframe.market/v1/items/" + item + "/orders" raw = requests.get(url) if raw.status_code != 200: - await ctx.send("Ordis覺得...指揮官是不是搞錯了什麼") + await ctx.send(lang["wfm.error.API"].format(self=jdata['self'],user=jdata['user'])) return else: raw = json.loads(raw.text.encode(encoding='UTF-8')) @@ -118,6 +134,12 @@ async def market(self, ctx, *item): for language in itemName: en = language['en'] tc = language['zh-hant'] + tax = language['trading_tax'] + ducats = language.get("ducats",None) + if ducats != None: + ducats = lang['wfm.ducats'].format(ducats=ducats) + else: + ducats = "" if en["item_name"] == items or tc['item_name'] == items: itemName = language['en'] itemName = itemName['item_name'] @@ -126,7 +148,10 @@ async def market(self, ctx, *item): for y in range(0, len(orderList) - x - 1): if (orderList[y]['platinum'] >orderList[y + 1]['platinum']): orderList[y], orderList[y + 1] = orderList[y + 1], orderList[y] - message = f"以下為{items}的五個最低價{Chinese_order_type[order_type]}家資料:\n" + if action == "sell": + for x in range(1,round(len(orderList)/2)): + orderList[x],orderList[len(orderList)-x] = orderList[len(orderList)-x],orderList[x] + message = lang["wfm.message.title"].format(items=items,order=price_order[action],order_type=local_order_type[order_type]) webhookID = jdata.get("webhook","Blank") webhookID = requests.get(webhookID) webhookID = json.loads(webhookID.text) @@ -142,16 +167,16 @@ async def market(self, ctx, *item): if orders['order_type'] == order_type and user['status'] == 'ingame' and orders['platform'] == 'pc': rank = orders.get("mod_rank","") if rank != "": - ChiRank = f"等級:{rank}" + localRank = f"等級:{rank}" rank = f"(rank {rank})" else: - ChiRank = "" - embed = DiscordEmbed(title=f"物品:{itemName}\t數量:{orders['quantity']}\t{ChiRank}",description=f"價格:{int(orders['platinum'])}",color=0x3b859a) - embed.add_embed_field(name="複製信息", value = f"\n/w {user['ingame_name']} Hi! I want to {action}: {itemName} {rank} for {int(orders['platinum'])} platinum. (warframe.market)\n") + localRank = "" + embed = DiscordEmbed(title=lang['wfm.embed.title'].format(itemName=items,quantity=orders['quantity'],localRank=localRank,tax=tax,ducats=ducats),description=lang['wfm.embed.description'].format(platinum=int(orders['platinum'])),color=0x3b859a) + embed.add_embed_field(name=lang["wfm.embed.field.cpMsg"], value = f"\n/w {user['ingame_name']} Hi! I want to {action}: {itemName} {rank} for {int(orders['platinum'])} platinum. (warframe.market)\n") avatar = user['avatar'] if avatar == None: avatar = "user/default-avatar.png" - embed.set_author(name=user['ingame_name'], icon_url="https://warframe.market/static/assets/"+avatar, url = "https://warframe.market/zh-hant/profile/"+user['ingame_name']) + embed.set_author(name=user['ingame_name'], icon_url="https://warframe.market/static/assets/"+avatar, url = f"https://warframe.market/{lang['wfm.link.language']}/profile/"+user['ingame_name']) webhook.add_embed(embed) count -= 1 response = webhook.execute() @@ -165,12 +190,12 @@ async def market(self, ctx, *item): if orders['order_type'] == order_type and user['status'] == 'ingame' and orders['platform'] == 'pc': rank = orders.get("mod_rank","") if rank != "": - ChiRank = f"等級:{rank}" - rank = f"(rank {rank})" + localRank = lang['wfm.rank'].format(rank=rank) + rank = f"(rank {rank}) " else: - ChiRank = "" - message+=f"```{Chinese_order_type[order_type]}\n玩家:{user['ingame_name']}\n物品:{itemName}\t數量:{orders['quantity']}\t{ChiRank}\n價格:{int(orders['platinum'])}\n" - message+=f"複製信息\n/w {user['ingame_name']} Hi! I want to {action}: {itemName} {rank} for {int(orders['platinum'])} platinum. (warframe.market)```\n" + localRank = "" + message+=lang['wfm.message.item'].format(user=user['ingame_name'],itemName=items,quantity=orders['quantity'],localRank=localRank,platinum=int(orders['platinum']),tax=tax,ducats=ducats) + message+=lang['wfm.message.cpMsg']+f"/w {user['ingame_name']} Hi! I want to {action}: {itemName} {rank}for {int(orders['platinum'])} platinum. (warframe.market)```\n" count -= 1 await ctx.send(message) diff --git a/cmds/wiki.py b/cmds/wiki.py index b8987f5..880b85f 100644 --- a/cmds/wiki.py +++ b/cmds/wiki.py @@ -2,7 +2,15 @@ from core.classes import Cog_Extension import discord from mwclient import Site +import json from fuzzywuzzy import process +from language import language as lang + +lang = lang() +lang = lang.langpref()['wiki'] + +with open('setting.json', 'r', encoding='utf8') as jfile: + jdata = json.load(jfile) zhURL = 'warframe.huijiwiki.com' tcURL = 'warframe.fandom.com' @@ -15,25 +23,25 @@ class wiki(Cog_Extension): tag = "Warframe" - @commands.command(name='update_wiki',brief="更新維基頁面列表",description="更新`wiki`語言維基的本地緩存頁面列表\n輸入`all`以更新所有維基") + @commands.command(name='update_wiki',brief=lang['update_wiki.brief'],description=lang['update_wiki.description']) async def update_wiki(self,ctx,*wiki): name = " ".join(wiki) if name == "zh"or"all": allpages= zh.allpages() - with open("dict/zh_pages.txt","w",encoding='utf8') as zh_pages: + with open("dict/zh_pages.txt","w") as zh_pages: for page in allpages: print(page.name,file = zh_pages) if name == "tc"or"all": allpages= tc.allpages() - with open("dict/tc_pages.txt","w",encoding='utf8') as tc_pages: + with open("dict/tc_pages.txt","w") as tc_pages: for page in allpages: print(page.name,file = tc_pages) if name == "en"or"all": allpages= en.allpages() - with open("dict/en_pages.txt","w",encoding='utf8') as en_pages: + with open("dict/en_pages.txt","w") as en_pages: for page in allpages: print(page.name,file = en_pages) - @commands.command(name='wiki',aliases=['維基'],brief="查詢維基頁面",description="查詢`page`的維基頁面") + @commands.command(name='wiki',aliases=lang['wiki.aliases'],brief=lang['wiki.brief'],description=lang['wiki.description']) async def wiki(self,ctx,*page): name = " ".join(page) with open("dict/zh_pages.txt","r") as zh_pages: @@ -50,25 +58,25 @@ async def wiki(self,ctx,*page): enpage.append(page) title,ratio = process.extractOne(name,zhpage) if ratio>75: - footer = "灰機" + footer = lang['wiki.footer.huiji'] URL = f"https://{zhURL}/wiki/{title}" else: title,ratio = process.extractOne(name,tcpage) if ratio>75: - footer = "繁體" + footer = lang['wiki.footer.tc'] URL = f"https://{tcURL}/zh-tw/wiki/{title}" else: title,ratio = process.extractOne(name,enpage) if ratio>75: - footer = "英文" + footer = lang['wiki.footer.en'] URL = f"https://{enURL}/wiki/{title}" else: - await ctx.send("Ordis找不到指揮官想要的頁面呢") + await ctx.send(lang['wiki.error.notFound'].format(self=jdata['self'],user=jdata['user'])) return - embed = discord.Embed(title=title,url=URL) + embed = discord.Embed(title=title,url=URL.replace(" ","_")) embed.set_footer(text=footer) await ctx.send(embed=embed) def setup(bot): - bot.add_cog(wiki(bot)) + bot.add_cog(wiki(bot)) \ No newline at end of file diff --git a/cmds/worldState.py b/cmds/worldState.py index c6aa9e7..61cf451 100644 --- a/cmds/worldState.py +++ b/cmds/worldState.py @@ -2,78 +2,82 @@ from core.classes import Cog_Extension import requests import json -import chinese_converter from datetime import datetime import discord +from language import language as lang +lang = lang() +lang = lang.langpref()['worldState'] class worldState(Cog_Extension): tag = "Warframe" def timeConv(self,expiry): h = int(expiry[11:13]) + 8 + if h >= 24: + h -=24 m = expiry[14:16] m = ("0" if len(m) == 1 else "") + m s = expiry[17:19] s = ("0" if len(s) == 1 else "") + s return(str(h)+":"+m) - @commands.command(name='POE',aliases=['夜靈平原時間' , 'poe'],brief="查詢夜靈平原時間",description="查詢夜靈平原目前日夜循環狀態和剩餘時間") + @commands.command(name='POE',aliases=lang['poe.aliases'],brief=lang['poe.brief'],description=lang['poe.description']) async def eidolontime(self,ctx): html = requests.get('https://api.warframestat.us/pc/cetusCycle').text data = json.loads(html) if (data["state"]=="day"): - desc = f"夜靈平原晚上將於{self.timeConv(data['expiry'])}開始\n距離夜靈平原晚上還有:" + data["timeLeft"] - embed = discord.Embed(title="夜靈平原-早上☀️",description=desc,color=0xbfdaf3) + desc = lang['poe.embed.description.day'].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang['poe.embed.title.day'],description=desc,color=0xbfdaf3) await ctx.send(embed=embed) elif (data["state"]=="night"): - desc = f"夜靈平原早上將於{self.timeConv(data['expiry'])}開始\n距離夜靈平原早上還有:" + data["timeLeft"] - embed = discord.Embed(title="夜靈平原-晚上️🌙",description=desc,color=0xaca9ca) + desc = lang['poe.embed.description.night'].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang['poe.embed.title.night'],description=desc,color=0xaca9ca) await ctx.send(embed=embed) - @commands.command(name='Earth',aliases=['地球時間'],brief="查詢地球時間",description="查詢地球目前日夜循環狀態和剩餘時間") + @commands.command(name='Earth',aliases=lang['earth.aliases'],brief=lang['earth.brief'],description=lang['earth.description']) async def earthtime(self,ctx): html = requests.get('https://api.warframestat.us/pc/tc/earthCycle').text data = json.loads(html) if (data["state"]=="day"): - desc = f"地球晚上將於{self.timeConv(data['expiry'])}開始\n距離地球晚上還有:" + data["timeLeft"] - embed = discord.Embed(title="地球-早上☀️",description=desc,color=0xbfdaf3) + desc = lang['earth.embed.description.day'].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang['earth.embed.title.day'],description=desc,color=0xbfdaf3) await ctx.send(embed=embed) elif (data["state"]=="night"): - desc = f"地球早上將於{self.timeConv(data['expiry'])}開始\n距離地球早上還有:" + data["timeLeft"] - embed = discord.Embed(title="地球-晚上️🌙",description=desc,color=0xaca9ca) + desc = lang['earth.embed.description.night'].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang['earth.embed.title.night'],description=desc,color=0xaca9ca) + await ctx.send(embed=embed) - @commands.command(name='Cambion',aliases=['魔裔禁地時間'],brief="查詢魔裔禁地時間",description="查詢魔裔禁地目前日夜循環狀態和剩餘時間") + @commands.command(name='Cambion',aliases=lang['cambion.aliases'],brief=lang['cambion.brief'],description=lang['cambion.description']) async def cambiontime(self,ctx): html = requests.get('https://api.warframestat.us/pc/cetusCycle').text data = json.loads(html) if (data["state"]=="day"): - desc = f"魔裔禁地Vome將於{self.timeConv(data['expiry'])}開始\n距離魔裔禁地Vome還有:" + data["timeLeft"] - embed = discord.Embed(title="魔裔禁地Fass",description=desc,color=0xda6d34) + desc =lang["cambion.embed.description.fass"].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang['cambion.embed.title.fass'],description=desc,color=0xda6d34) await ctx.send(embed=embed) elif (data["state"]=="night"): - desc = f"魔裔禁地Fass將於{self.timeConv(data['expiry'])}開始\n距離魔裔禁地Fass還有:" + data["timeLeft"] - embed = discord.Embed(title="魔裔禁地Vome",description=desc,color=0x458691) + desc = lang['cambion.embed.description.vome'].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang['cambion.embed.title.vome'],description=desc,color=0x458691) await ctx.send(embed=embed) - @commands.command(name='Orb',aliases=['奧布山谷時間' , 'orb'],brief="查詢奧布山谷時間",description="查詢奧布山谷目前日夜循環狀態和剩餘時間") + @commands.command(name='Orb',aliases=lang["orb.aliases"],brief=lang['orb.brief'],description=lang['orb.description']) async def orbtime(self,ctx): html = requests.get('https://api.warframestat.us/pc/vallisCycle',headers={'Accept-Language':'tc','Cache-Control': 'no-cache'}).text data = json.loads(html) if(data['state']=='cold'): - desc = f"奧布山谷溫暖將於{self.timeConv(data['expiry'])}開始\n距離奧布山谷溫暖還有:" + data["timeLeft"] - embed = discord.Embed(title="奧布山谷寒冷",description=desc,color=0x6ea7cd) + desc = lang["orb.embed.description.cold"].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang["orb.embed.title.cold"],description=desc,color=0x6ea7cd) await ctx.send(embed=embed) elif(data['state']=='warm'): - desc = f"奧布山谷寒冷將於{self.timeConv(data['expiry'])}開始\n距離奧布山谷寒冷還有:" + data["timeLeft"] - embed = discord.Embed(title="奧布山谷溫暖",description=desc,color=0xd9b4a1) + desc = lang["orb.embed.description.warm"].format(expiry=self.timeConv(data['expiry'])) + data["timeLeft"] + embed = discord.Embed(title=lang["orb.embed.title.warm"],description=desc,color=0xd9b4a1) await ctx.send(embed=embed) - @commands.command(name="Arbitration",aliases=['仲裁'],brief="查詢仲裁任務",description="查詢當前仲裁任務與剩餘時間\n**此功能由於API不穩定,返回數據未必準確**") + @commands.command(name="Arbitration",aliases=lang["arbitration.aliases"],brief=lang['arbitration.brief'],description=lang['arbitration.description']) async def arbitration(self,ctx): raw = requests.get("https://api.warframestat.us/pc/tc/arbitration",headers={'Accept-Language':'zh'}) text = raw.text - text = chinese_converter.to_traditional(text) data = json.loads(text) expiry = data['expiry'] timeLeft = datetime.strptime(expiry,'%Y-%m-%dT%X.000Z') @@ -81,23 +85,22 @@ async def arbitration(self,ctx): timeLeft = timeLeft-now minutes = int((timeLeft.seconds - timeLeft.seconds%60)/60) seconds = timeLeft.seconds%60 - embed = discord.Embed(title="仲裁",description=f"任務:{data['type']}",color=0x302f36) - embed.add_field(name=f"節點:{data['node']}",value=f"敵人:{data['enemy']}\n剩餘時間:{minutes}分鐘{seconds}秒") + embed = discord.Embed(title=lang["arbitration.embed.title"],description=lang['arbitration.embed.description'].format(type=data['type']),color=0x302f36) + embed.add_field(name=lang['arbitration.embed.field.name'].format(node=data['node']),value=lang["arbitration.embed.field.value"].format(enemy=data['enemy'],minutes=minutes,seconds=seconds)) await ctx.send(embed=embed) - @commands.command(name='Sortie',aliases=['突擊' , 'sortie'],brief="查詢突擊任務",description="查詢目前突擊任務和剩餘時間") + @commands.command(name='Sortie',aliases=lang['sortie.aliases'],brief=lang['sortie.brief'],description=lang['sortie.description']) async def sortie(self,ctx): count = 1 raw = requests.get('https://api.warframestat.us/pc/zh/sortie',headers={'Accept-Language':'tc'}) text = raw.text - text = chinese_converter.to_traditional(text) data = json.loads(text) - embed = discord.Embed(title=f"突擊剩餘時間:{data['eta']}",description=f"{data['boss']}的部隊,{data['faction']}陣營",color=0xff9500) + embed = discord.Embed(title=lang["sortie.embed.title"].format(eta=data['eta'],),description=lang['sortie.embed.description'].format(boss=data['boss'],faction=data['faction']),color=0xff9500) for missions in data['variants']: node = missions['node'] missionType= missions['missionType'] modifier = missions['modifier'] - embed.add_field(name=f"突擊{count}:\n節點:{node} 等級{35+15*count}-{40+20*count}",value=f"任務:{missionType}\n狀態:{modifier}",inline=False) + embed.add_field(name=lang['sortie.embed.field.name'].format(count=count,node=node,lower=35+15*count,upper=40+20*count),value=lang['sortie.embed.field.value'].format(missionType=missionType,modifier=modifier),inline=False) count += 1 await ctx.send(embed=embed) diff --git a/language.py b/language.py new file mode 100644 index 0000000..e74f43d --- /dev/null +++ b/language.py @@ -0,0 +1,14 @@ +import json +import requests + +class language(): + def __init__(self): + self.zh_hant = json.loads(requests.get("https://raw.githubusercontent.com/lonnstyle/DiscordBotExt/main/zh-hant.json").text) + self.pref = json.load(open("setting.json",'r',encoding='utf8')) + self.pref = self.pref.get("language","zh-hant") + def langpref(self): + if self.pref == 'zh-hant': + return self.zh_hant + else: + return json.load(open(self.pref,"r",encoding='utf8')) + \ No newline at end of file diff --git a/main.py b/main.py index a2a187b..d5efebb 100644 --- a/main.py +++ b/main.py @@ -7,32 +7,36 @@ import requests import asyncio import sys +from language import language as lang + +lang = lang() +lang = lang.langpref()['main'] intents = discord.Intents.all() #載入設定檔 with open('setting.json', 'r', encoding='utf8') as jfile: jdata = json.load(jfile) - bot = commands.Bot(command_prefix=commands.when_mentioned_or(jdata['command_prefix']),intents = intents) start_time = datetime.now() +version = "v2.1.0" @bot.event async def on_ready(): - print(">> 目前版本:v2.0.3 <<") - print(">> OrdisBeta is online <<") - activity = discord.Activity(type=discord.ActivityType.watching,name = "指揮官帥氣的臉龐") - await bot.change_presence(activity=activity) - while(1): - await asyncio.sleep(60) - requests.get("http://127.0.0.1:8080/") + print(lang['startup.version'].format(version=version)) + print(">> OrdisBeta is online <<") + activity = discord.Activity(type=discord.ActivityType.watching,name = jdata['watching']) + await bot.change_presence(activity=activity) + while(1): + await asyncio.sleep(60) + requests.get("http://127.0.0.1:8080/") #---------------------------------------------------------------------------- bot.remove_command('help') #help指令 -@bot.command(name="help" , aliases=['幫助' , '機器人功能' , 'HELP'] ,description="展示`command`的幫助信息", brief="展示幫助列表") +@bot.command(name="help" , aliases=lang['help.aliases'] ,description=lang['help.description'], brief=lang['help.brief']) async def help(ctx, command:str="all", page:int=1): fields = 0 - embed = discord.Embed(title="幫助列表",color=0xccab2b) + embed = discord.Embed(title=lang['help.embed.title'],color=0xccab2b) embed.set_author(name="Patreon", url="https://patreon.com/join/lonnstyle", icon_url="https://i.imgur.com/CCYuxwH.png") if command == "all": for command in bot.commands: @@ -40,7 +44,7 @@ async def help(ctx, command:str="all", page:int=1): if (page-1)*25使用") +@bot.command(name= 'disconnect', aliases=lang['disconnect.aliases'],brief=lang['disconnect.brief'],description=lang['disconnect.description'].format(owner=bot.owner_id)) async def turn_off_bot(ctx): - if ctx.message.author.id == jdata['owner']: - print(utc_8_date_str + '機器人已關閉') - await ctx.send(utc_8_date_str + '\n機器人已關閉') #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< + if await bot.is_owner(ctx.author): + await ctx.send(utc_8_date_str + '\n'+lang['disconnect.disconnected']) #<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< await bot.close() else: - owner = jdata['owner'] - await ctx.send(f'權限不足 本指令只提供給Ordis擁有者 \n擁有者為 <@{owner}>') + await ctx.send(embed=discord.Embed(title=lang['disconnect.error.title'],description=lang['disconnect.error.description'].format(owner=bot.owner_id),color=0xff0000)) #-------------------------------- -@bot.command(name='status', aliases=['debug'],brief="除錯信息",description="回報當前機器人狀態信息進行除錯") +@bot.command(name='status', aliases=['debug'],brief=lang['status.brief'],description=lang['status.description'].format(owner=bot.owner_id)) async def status(ctx): if await bot.is_owner(ctx.message.author): - embed = discord.Embed(title="目前狀態:") - embed.add_field(name="目前延遲",value=f"{round(bot.latency*1000)}ms",inline=False) + embed = discord.Embed(title=lang['status.embed.title']) + embed.add_field(name=lang['status.embed.field.ping'],value=f"{round(bot.latency*1000)}ms",inline=False) perms = ">>> " for name,value in ctx.channel.permissions_for(ctx.me): if value == True: perms += name + '\n' - embed.add_field(name="本機權限",value=perms,inline=True) + embed.add_field(name=lang['status.embed.field.perms'],value=perms,inline=True) exts = ">>> " for ext in bot.extensions: exts += ext.replace("cmds.","")+'\n' - embed.add_field(name="已加載擴展",value=exts,inline=True) + embed.add_field(name=lang['status.embed.field.exts'],value=exts,inline=True) uptime = datetime.now()-start_time - embed.set_footer(text=f"在線時間:{uptime.days}天{int(uptime.seconds/3600)}:{int(uptime.seconds%3600/60)}:{uptime.seconds%3600%60}") + embed.set_footer(text=lang['status.embed.footer.time'].format(days=uptime.days,hours=int(uptime.seconds/3600),minutes=int(uptime.seconds%3600/60),seconds=uptime.seconds%3600%60)+version) await ctx.send(embed=embed) else: - await ctx.send(embed=discord.Embed(title="權限不足",description='本指令只提供給伺服器傭有者 \n本伺服器擁有者為 <@' + str(ctx.guild.owner_id) + '>')) + await ctx.send(embed=discord.Embed(title=lang['status.error.title'],description=lang['status.error.description'].format(owner=bot.owner_id))) + for filename in os.listdir('./cmds'): if filename.endswith('.py'): @@ -149,5 +159,5 @@ async def status(ctx): if __name__ == "__main__": - keep_alive.keep_alive() - bot.run(jdata['TOKEN']) + keep_alive.keep_alive() + bot.run(jdata['TOKEN']) \ No newline at end of file diff --git a/setting.json b/setting.json index 2c99a55..617af04 100644 --- a/setting.json +++ b/setting.json @@ -1,6 +1,9 @@ { - "TOKEN": <你的Token>, - "command_prefix":<你想要的指令前綴>, - "owner":<你的Discord ID>, - "webhook":<你想要弄的Webhook頻道URL> -} + "TOKEN": "", + "command_prefix":"", + "webhook":"", + "user":"", + "self":"", + "watching":"", + "publish": +} \ No newline at end of file diff --git a/zh-hant.json b/zh-hant.json new file mode 100644 index 0000000..8563410 --- /dev/null +++ b/zh-hant.json @@ -0,0 +1,210 @@ +{ + "main":{ + "startup.version" : ">> 目前版本:{version} <<", + "help.aliases" : ["幫助" , "機器人功能" , "HELP"], + "help.description" : "展示`command`的幫助信息", + "help.brief" : "展示幫助列表", + "help.embed.title" : "幫助列表", + "help.embed.footer" : "使用{command_prefix}help <指令名稱>查看更多信息\n第{page}/{total}頁", + "help.not_found" : "找不到{user}要問的呢", + "load.aliases" : ["載入" , "載入模組" , "啟用"], + "load.brief" : "載入擴展庫", + "load.description" : "載入`extension`擴展庫", + "load.loaded" : "已加載:{extension}", + "load.error.title" : "權限不足", + "load.error.description" : "本指令只提供給機器人擁有者\n本機器人擁有者為<@{owner}>", + "unload.aliases" : ["卸載" , "卸載模組" , "停用"], + "unload.brief" : "卸載擴展庫", + "unload.description" : "卸載`extension`擴展庫", + "unload.unloaded" : "已卸載:{extension}", + "unload.error.title" : "權限不足", + "unload.error.description" : "本指令只提供給機器人擁有者\n本機器人擁有者為<@{owner}>", + "reload.aliases" : ["重載" , "重載模組" , "重新載入模組", "重新加載", "重啟"], + "reload.brief" : "重載擴展庫", + "reload.description" : "重新載入`extension`擴展庫", + "reload.reloaded" : "已重新載入:{extension}", + "reload.error.title" : "權限不足", + "reload.error.description" : "本指令只提供給機器人擁有者\n本機器人擁有者為<@{owner}>", + "disconnect.aliases" : ["disable","shutdown","關閉機器人","關機", "關閉"], + "disconnect.brief" : "關閉機器人", + "disconnect.description" : "機器人關機\n僅供<@{owner}>使用", + "disconnect.disconnected" : "機器人已關閉", + "disconnect.error.title" : "權限不足", + "disconnect.error.description" : "本指令只提供給機器人擁有者\n本機器人擁有者為<@{owner}>", + "status.brief" : "除錯信息", + "status.description" : "回報當前機器人狀態信息進行除錯", + "status.embed.title" : "目前狀態:", + "status.embed.field.ping" : "目前延遲", + "status.embed.field.perms" : "本機權限", + "status.embed.field.exts" : "已加載擴展", + "status.embed.footer.time" : "在線時間:{days}天{hours}:{minutes}:{seconds}\n", + "status.error.title" : "權限不足", + "status.error.description" : "本指令只提供給伺服器擁有者\n本伺服器擁有者為<@{owner}>" + }, + "admin":{ + "clear.aliases":["clean" , "清除"], + "clear.brief":"刪除聊天記錄", + "clear.description":"clear [指定數量]\n刪除指定數量的聊天記錄", + "clear.cleared":"在<<{channel}>>頻道使用了clear指令刪除了{num}個對話", + "clear.error.title":"權限不足", + "clear.error.description":"本指令只提供給機器人傭有者 \n本機器人擁有者為 <@{owner}>" + }, + "baro":{ + "rawDict.URL":"https://raw.githubusercontent.com/pa001024/riven-mirror/dev/src/i18n/lang/zh-Hant.json", + "baro.aliases":["奸商" , "Baro"], + "baro.brief":"虛空商人信息", + "baro.description":"查詢虛空商人Baro Ki'Teer目前狀態\t如已經抵達中繼站則會顯示所攜帶商品列表", + "baro.time.day":"天", + "baro.time.hour":"小時", + "baro.time.minute":"分鐘", + "baro.time.second":"秒", + "baro.item":"物品:{name}\n杜卡德金幣:{ducats}\t現金:{credits}\n", + "baro.arrived":"Baro Ki'Teer 已經到達{location},停留時間為{stay}\t帶來的商品如下:", + "baro.arrival":"Baro Ki'Teer會在{arrive}後抵達{location}" + }, + "common":{ + "ping.aliases":["延遲" , "機器人延遲" , "delay"], + "ping.brief":"測試延遲", + "ping.description":"顯示當前機器人處理信息的延遲值", + "ping.embed.title":"當前本機延遲為", + "ping.latency":"{latency} 毫秒 (ms)", + "sayd.aliases":["說" , "機器人說"], + "sayd.brief":"復讀", + "sayd.description":"讓機器人代替你說出`msg`的內容", + "poll.aliases":["投票"], + "poll.brief":"發起投票", + "poll.description":"讓機器人發起一項投票", + "poll.error.title":"錯誤信息", + "poll.error.description.same":"兩個一樣你要投什麼?", + "poll.error.description.emoji":"請確保選項為emoji" + }, + "event":{ + "role.aliases":["身份組"], + "role.brief":"新增可分發的身份組", + "role.description":"新增可自動分發的身份組", + "role.error.title":"發生錯誤", + "role.error.description":"請檢查內容", + "reactionRole.aliases":["rr"], + "reactionRole.brief":"指定自動身份組訊息", + "reactionRole.description":"指定可自動分發身份組的訊息", + "onMessage.say":"說:" + }, + "logup":{ + "reloadlog.reloaded":"已重新加載" + }, + "rivenPrice":{ + "api.header":{"Language":"zh-hant"}, + "riven.aliases":["紫卡","紫卡查詢"], + "riven.brief":"查詢裂罅價格", + "riven.description":"查詢`weapon`裂罅價格", + "riven.error.title":"出錯啦!", + "riven.error.description":"查到...{self}發生錯誤...API出錯!", + "riven.message.title":"以下為{userInput}紫卡的查詢結果(按價格由低至高順序)\n", + "riven.message.rivenName":"```\n紫卡名稱:{userInput} {rivenName}\n", + "riven.message.owner":"賣家:{ownerName}\n", + "riven.message.rank":"等級:{rank}\n", + "riven.message.reroll":"迴圈次數:{rerolls}\n", + "riven.embed.title":"紫卡名稱:{userInput} {rivenName}", + "riven.embed.description":"等級:{rank} 迴圈次數:{rerolls}", + "riven.link.language":"zh-hant", + "riven.message.topbid":"目前競標:{top_bid}\n", + "riven.embed.field.topbid":"目前競標:", + "riven.message.price":"價格:{buyout_price}\n", + "riven.embed.field.price":"價格:", + "riven.message.starting":"起標價格:{starting_price}\n", + "riven.message.buyout":"買斷價格:{buyout_price}\n", + "riven.embed.field.starting":"起標價格:", + "riven.embed.field.buyout":"買斷價格", + "riven.message.attr.pos":"正面詞條:{attribute} {value}\n", + "riven.message.attr.neg":"負面詞條:{attribute} {value}\n", + "riven.embed.attr.pos":"正面詞條:", + "riven.embed.attr.neg":"負面詞條:" + }, + "wfm":{ + "api.header":{"Language":"zh-hant"}, + "local_order_type":{"buy":"買","sell":"賣"}, + "price_order":{"buy":"低","sell":"高"}, + "translate.aliases":["trans","翻譯"], + "translate.brief":"進行中英文翻譯", + "translate.description":"翻譯`item`於[wf.m](https://warframe.market)上的名稱", + "translate.error.notFound":"{self}沒找到{user}說的物品呢", + "translate.language.en":"英文", + "translate.language.local":"中文", + "translate.error.noTrans":"{self}也不太清楚翻譯是什麼呢", + "translate.translate.message":"`{item}`的{language}翻譯為 `{translate}`", + "wfm.aliases":["wm", "市場查詢"], + "wfm.brief":"查詢物品價格", + "wfm.description":"查詢`args`於[wf.m](https://warframe.market)上的價格\n`args`可填以下參數:\n`type`買賣類別,`item`物品(必填),`rank`等級", + "wfm.buy":"買", + "wfm.sell":"賣", + "wfm.error.unknownOrder":"{user}是要買還是賣呢?", + "wfm.error.tooManyArgs":"{user}說的太多了,{self}不是很懂呢", + "wfm.error.unknownItem":"{self}不太清楚指揮官說的什麼呢", + "wfm.error.outOfRank":"{user}所輸入的等級超出物品最高等級呢 0.0", + "wfm.error.API":"{self}覺得...{user}是不是搞錯了什麼", + "wfm.ducats":"杜卡德金幣:{ducats}", + "wfm.message.title":"以下為{items}的五個最{order}價{order_type}家資料:\n", + "wfm.embed.title":"物品:{itemName}\t數量:{quantity}\t{localRank}\n交易稅:{tax}\t{ducats}", + "wfm.embed.description":"價格:{platinum}", + "wfm.embed.field.cpMsg":"複製信息", + "wfm.link.language":"zh-hant", + "wfm.rank":"等級:{rank}", + "wfm.message.item":"```玩家:{user}\n物品:{itemName}\t數量:{quantity}\t{localRank}\n價格:{platinum}\n交易稅:{tax}\t{ducats}\n", + "wfm.message.cpMsg":"複製信息\n" + }, + "wiki":{ + "update_wiki.brief":"更新維基頁面列表", + "update_wiki.description":"更新`wiki`語言維基的本地緩存頁面列表\n輸入`all`以更新所有維基", + "wiki.aliases":["維基"], + "wiki.brief":"查詢維基頁面", + "wiki.description":"查詢`page`的維基頁面", + "wiki.footer.huiji":"灰機", + "wiki.footer.tc":"繁體", + "wiki.footer.en":"英文", + "wiki.error.notFound":"{self}找不到{user}想要的頁面呢" + }, + "worldState":{ + "poe.aliases":["夜靈平原時間" , "poe"], + "poe.brief":"查詢夜靈平原時間", + "poe.description":"查詢夜靈平原目前日夜循環狀態和剩餘時間", + "poe.embed.description.day":"夜靈平原晚上將於{expiry}開始\n距離夜靈平原晚上還有:", + "poe.embed.title.day":"夜靈平原-早上☀️", + "poe.embed.description.night":"夜靈平原早上將於{expiry}開始\n距離夜靈平原早上還有:", + "poe.embed.title.night":"夜靈平原-晚上️🌙", + "earth.aliases":["地球時間"], + "earth.brief":"查詢地球時間", + "earth.description":"查詢地球目前日夜循環狀態和剩餘時間", + "earth.embed.description.day":"地球晚上將於{expiry}開始\n距離地球晚上還有:", + "earth.embed.title.day":"地球-早上☀️", + "earth.embed.description.night":"地球早上將於{expiry}開始\n距離地球早上還有:", + "earth.embed.title.night":"地球-晚上️🌙", + "cambion.aliases":["魔裔禁地時間"], + "cambion.brief":"查詢魔裔禁地時間", + "cambion.description":"查詢魔裔禁地目前日夜循環狀態和剩餘時間", + "cambion.embed.description.fass":"魔裔禁地Vome將於{expiry}開始\n距離魔裔禁地Vome還有:", + "cambion.embed.title.fass":"魔裔禁地Fass", + "cambion.embed.description.vome":"魔裔禁地Fass將於{expiry}開始\n距離魔裔禁地Fass還有:", + "cambion.embed.title.vome":"魔裔禁地Vome", + "orb.aliases":["奧布山谷時間" , "orb"], + "orb.brief":"查詢奧布山谷時間", + "orb.description":"查詢奧布山谷目前日夜循環狀態和剩餘時間", + "orb.embed.description.cold":"奧布山谷溫暖將於{expiry}開始\n距離奧布山谷溫暖還有:", + "orb.embed.title.cold":"奧布山谷寒冷", + "orb.embed.description.warm":"奧布山谷寒冷將於{expiry}開始\n距離奧布山谷寒冷還有:", + "orb.embed.title.warm":"奧布山谷溫暖", + "arbitration.aliases":["仲裁"], + "arbitration.brief":"查詢仲裁任務", + "arbitration.description":"查詢當前仲裁任務與剩餘時間\n**此功能由於API不穩定,返回數據未必準確**", + "arbitration.embed.title":"仲裁", + "arbitration.embed.description":"任務:{type}", + "arbitration.embed.field.name":"節點:{node}", + "arbitration.embed.field.value":"敵人:{enemy}\n剩餘時間:{minutes}分鐘{seconds}秒", + "sortie.aliases":["突擊" , "sortie"], + "sortie.brief":"查詢突擊任務", + "sortie.description":"查詢目前突擊任務和剩餘時間", + "sortie.embed.title":"突擊剩餘時間:{data['eta']}", + "sortie.embed.description":"{boss}的部隊,{faction}陣營", + "sortie.embed.field.name":"突擊{count}:\n節點:{node} 等級{lower}-{upper}", + "sortie.embed.field.value":"任務:{missionType}\n狀態:{modifier}" + } +} \ No newline at end of file