diff --git a/README.md b/README.md index a536d3d..cfc201a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ 中文 | [English](docs/README-en-US.md) | [日本語](docs/README-ja-JP.md) # MediaWiki-Bot -MediaWiki的多语言QQ查询机器人 -可以对使用MediaWiki搭建的站点进行信息查询,支持多种语言 +通过聊天软件对MediaWiki进行查询信息的机器人 +可以对使用聊天软件对MediaWiki搭建的站点进行信息查询,支持多种语言,跨平台兼容,支持QQ,Telegram 基于Gin和[mirai-api-http](https://github.com/project-mirai/mirai-api-http)制作 @@ -12,16 +12,19 @@ MediaWiki的多语言QQ查询机器人 ## 启动 1. 从[Releases](https://github.com/nyancatda/MediaWiki-Bot/releases)下载最新构建 -1. 在程序同级目录创建[config.yml](https://github.com/nyancatda/MediaWiki-Bot#configyml%E6%96%87%E4%BB%B6%E6%A8%A1%E6%9D%BF),并按照模板填写信息 -1. 配置[mirai-api-http](https://github.com/nyancatda/MediaWiki-Bot#%E9%85%8D%E7%BD%AEmirai-api-http) +1. 在程序同级目录创建[config.yml](#configyml%E6%96%87%E4%BB%B6%E6%A8%A1%E6%9D%BF),并按照模板填写信息 +1. 配置[聊天软件](#聊天软件配置) 1. 运行程序 -## 配置mirai-api-http +## 聊天软件配置 +*请至少配置一个聊天软件,否则机器人将无法工作* +### mirai-api-http(QQ) 1. 启用http和webhook 1. 启用enableVerify,并设置VerifyKey 1. 将webhook地址设置为http://127.0.0.1:+指定的机器人运行端口 -setting.yml模板*仅供参考* +setting.yml模板 +*仅供参考* ``` adapters: - http @@ -40,6 +43,10 @@ adapterSettings: destinations: - 'http://127.0.0.1:8000/' ``` +### Telegram +1. 设置Telegram WebHook上报地址为机器人接收地址,具体请查看[官方文档](https://core.telegram.org/bots/api#setwebhook) + *注意,Telegram的WebHook上报地址需要`https`,这可能需要需要对机器人接收上报的地址做反向代理* +1. 如果你的服务器位于中国大陆,你还需要搭建Telegram Bot API的反向代理服务,关于如何搭建,请查看[TelegramBotAPI反向代理服务器搭建](docs/Telegram/ReverseProxyAPI.md) ## config.yml文件模板 ``` @@ -49,13 +56,19 @@ Run: #指定机器人的语言 #中文:zh-CN,英语:en-US,日语ja-JP Language: zh-CN -QQBot: - #HttpAPI地址 - APILink: http://127.0.0.1:8888 - #机器人QQ号 - BotQQNumber: 1000000000 - #HttpAPI的VerifyKey - VerifyKey: 5eadce46qw58 +SNS: + QQ: + #HttpAPI地址 + APILink: http://127.0.0.1:8888 + #机器人QQ号 + BotQQNumber: 1000000000 + #HttpAPI的VerifyKey + VerifyKey: 5eadce46qw58 + Telegram: + #机器人toekn + Token: 688975899:DDFqpsdMwunUvwAsxzDTzl8z_UkYzStrewM + #TelegramAPI地址 + BotAPILink: https://api.telegram.org/ #Wiki链接,支持多个,第一个为主Wiki Wiki: - diff --git a/docs/README-en-US.md b/docs/README-en-US.md index 6e371c0..faa21e5 100644 --- a/docs/README-en-US.md +++ b/docs/README-en-US.md @@ -1,7 +1,7 @@ [中文](https://github.com/nyancatda/MediaWiki-Bot) | English | [日本語](README-ja-JP.md) # MediaWiki-Bot -QQ query bot on MedisWiki -Can query MediaWiki site for information, support multiple languages +通过聊天软件对MediaWiki进行查询信息的机器人 +可以对使用聊天软件对MediaWiki搭建的站点进行信息查询,支持多种语言,跨平台兼容,支持QQ,Telegram Based on Gin snd [mirai-api-http](https://github.com/project-mirai/mirai-api-http) @@ -12,16 +12,19 @@ Based on Gin snd [mirai-api-http](https://github.com/project-mirai/mirai-api-htt ## Start 1. Download the latest [Releases](https://github.com/nyancatda/MediaWiki-Bot/releases). -1. Create [config.yml](https://github.com/nyancatda/MediaWiki-Bot#configyml%E6%96%87%E4%BB%B6%E6%A8%A1%E6%9D%BF) in the program's sibling directory. And follow the template to fill in the information. -1. [Configure the mirai-api-http](https://github.com/nyancatda/MediaWiki-Bot/blob/main/docs/README-en-US.md#%E9%85%8D%E7%BD%AEmirai-api-http) +1. Create [config.yml](#configyml-template) in the program's sibling directory. And follow the template to fill in the information. +1. 配置[聊天软件](#聊天软件配置) 1. Run the program. -## Configure the mirai-api-http +## 聊天软件配置 +*请至少配置一个聊天软件,否则机器人将无法工作* +### mirai-api-http(QQ) 1. Enable the http and webhook 1. Enable the enableVerify and enter your VerifyKey 1. Fill the webhook address as: http://127.0.0.1:+port -setting.yml *The template is for reference only* +setting.yml +*The template is for reference only* ``` adapters: - http @@ -40,6 +43,10 @@ adapterSettings: destinations: - 'http://127.0.0.1:8000/' ``` +### Telegram +1. 设置Telegram WebHook上报地址为机器人接收地址,具体请查看[官方文档](https://core.telegram.org/bots/api#setwebhook) + *注意,Telegram的WebHook上报地址需要`https`,这可能需要需要对机器人接收上报的地址做反向代理* +1. 如果你的服务器位于中国大陆,你还需要搭建Telegram Bot API的反向代理服务,关于如何搭建,请查看[TelegramBotAPI反向代理服务器搭建](docs/Telegram/ReverseProxyAPI.md) ## config.yml template ``` @@ -49,13 +56,19 @@ Run: #Language #Chinese:zh-CN,English:en-US,Japanese:ja-JP Language: zh-CN -QQBot: - #HttpAPI address - APILink: http://127.0.0.1:8888 - #The robot QQ number - BotQQNumber: 1000000000 - #HttpAPI‘s VerifyKey - VerifyKey: 5eadce46qw58 +SNS: + QQ: + #HttpAPI address + APILink: http://127.0.0.1:8888 + #The robot QQ number + BotQQNumber: 1000000000 + #HttpAPI‘s VerifyKey + VerifyKey: 5eadce46qw58 + Telegram: + #机器人toekn + Token: 688975899:DDFqpsdMwunUvwAsxzDTzl8z_UkYzStrewM + #TelegramAPI地址 + BotAPILink: https://api.telegram.org/ #Wiki urls. Multiple URLs can be added. The first one is the default Wiki Wiki: - diff --git a/docs/README-ja-JP.md b/docs/README-ja-JP.md index 6c7fdc4..2695f3e 100644 --- a/docs/README-ja-JP.md +++ b/docs/README-ja-JP.md @@ -1,7 +1,7 @@ [中文](https://github.com/nyancatda/MediaWiki-Bot) | [English](README-en-US.md) | 日本語 # MediaWiki-Bot -MediaWikiの多言語QQ検索ボット -MediaWikiを使うWebページの検索が可能 +通过聊天软件对MediaWiki进行查询信息的机器人 +可以对使用聊天软件对MediaWiki搭建的站点进行信息查询,支持多种语言,跨平台兼容,支持QQ,Telegram Ginと[mirai-api-http](https://github.com/project-mirai/mirai-api-http)に基づいて作られた @@ -12,16 +12,19 @@ Ginと[mirai-api-http](https://github.com/project-mirai/mirai-api-http)に基づ ## スタートアップ 1. [Releases](https://github.com/nyancatda/MediaWiki-Bot/releases)から最新バージョンの構築をダウンロードする -1. プログラムの同じディレクトリで[config.yml](https://github.com/nyancatda/MediaWiki-Bot#configyml%E6%96%87%E4%BB%B6%E6%A8%A1%E6%9D%BF)を作成して、それからテンプレートにしたがってメッセージを入力する -1. [mirai-api-http](https://github.com/nyancatda/MediaWiki-Bot#%E9%85%8D%E7%BD%AEmirai-api-http)を設定する +1. プログラムの同じディレクトリで[config.yml](#configyml%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%83%86%E3%83%B3%E3%83%97%E3%83%AC%E3%83%BC%E3%83%88)を作成して、それからテンプレートにしたがってメッセージを入力する +1. 配置[聊天软件](#聊天软件配置) 1. プログラムを実行する -## mirai-api-httpの設定 +## 聊天软件配置 +*请至少配置一个聊天软件,否则机器人将无法工作* +### mirai-api-http(QQ) 1. httpとwebhookを起動する 1. enableVerifyを起動してから、VerifyKeyを設定する 1. webhookアドレスをhttp://127.0.0.1:+指定されたボットのポート に設定する -setting.ymlテンプレート*参考だけ* +setting.ymlテンプレート +*参考だけ* ``` adapters: - http @@ -40,6 +43,10 @@ adapterSettings: destinations: - 'http://127.0.0.1:8000/' ``` +### Telegram +1. 设置Telegram WebHook上报地址为机器人接收地址,具体请查看[官方文档](https://core.telegram.org/bots/api#setwebhook) + *注意,Telegram的WebHook上报地址需要`https`,这可能需要需要对机器人接收上报的地址做反向代理* +1. 如果你的服务器位于中国大陆,你还需要搭建Telegram Bot API的反向代理服务,关于如何搭建,请查看[TelegramBotAPI反向代理服务器搭建](docs/Telegram/ReverseProxyAPI.md) ## config.ymlファイルテンプレート ``` @@ -49,13 +56,19 @@ Run: #ボットの言語を選ぶ #中国語:zh-CN,英語:en-US,日本語ja-JP Language: zh-CN -QQBot: - #HttpAPIアドレス - APILink: http://127.0.0.1:8888 - #ボットのQQアプリ番号 - BotQQNumber: 1000000000 - #HttpAPIのVerifyKey - VerifyKey: 5eadce46qw58 +SNS: + QQ: + #HttpAPIアドレス + APILink: http://127.0.0.1:8888 + #ボットのQQアプリ番号 + BotQQNumber: 1000000000 + #HttpAPIのVerifyKey + VerifyKey: 5eadce46qw58 + Telegram: + #机器人toekn + Token: 688975899:DDFqpsdMwunUvwAsxzDTzl8z_UkYzStrewM + #TelegramAPI地址 + BotAPILink: https://api.telegram.org/ #Wikiアドレス 複数、一番目が優先のWiki Wiki: - diff --git a/docs/Telegram/ReverseProxyAPI-en-US.md b/docs/Telegram/ReverseProxyAPI-en-US.md new file mode 100644 index 0000000..1717a78 --- /dev/null +++ b/docs/Telegram/ReverseProxyAPI-en-US.md @@ -0,0 +1,40 @@ +[中文](ReverseProxyAPI.md) | English | [日本語](ReverseProxyAPI-ja-JP.md) +# TelegramBotAPI反向代理服务器搭建 +*本篇教程将告诉你如何使用CloudFlare Workers搭建一个自己的TelegramBotAPI反向代理服务器* +1. 前往[CloudFlare Workers](https://workers.cloudflare.com/)官网,注册一个账号,并新建一个Worker +2. 在脚本中写入以下代码 +``:你的机器人token +``` +const whitelist = ["/bot"]; +const tg_host = "api.telegram.org"; + +addEventListener('fetch', event => { + event.respondWith(handleRequest(event.request)) +}) + +function validate(path) { + for (var i = 0; i < whitelist.length; i++) { + if (path.startsWith(whitelist[i])) + return true; + } + return false; +} + +async function handleRequest(request) { + var u = new URL(request.url); + u.host = tg_host; + if (!validate(u.pathname)) + return new Response('Unauthorized', { + status: 403 + }); + var req = new Request(u, { + method: request.method, + headers: request.headers, + body: request.body + }); + const result = await fetch(req); + return result; +} +``` +3. 点击保存并部署 +4. 在将配置文件中的`BotAPILink`修改为这个Worker的地址即可 \ No newline at end of file diff --git a/docs/Telegram/ReverseProxyAPI-ja-JP.md b/docs/Telegram/ReverseProxyAPI-ja-JP.md new file mode 100644 index 0000000..65d8ba3 --- /dev/null +++ b/docs/Telegram/ReverseProxyAPI-ja-JP.md @@ -0,0 +1,40 @@ +[中文](ReverseProxyAPI.md) | [English](ReverseProxyAPI-en-US.md) | 日本語 +# TelegramBotAPI反向代理服务器搭建 +*本篇教程将告诉你如何使用CloudFlare Workers搭建一个自己的TelegramBotAPI反向代理服务器* +1. 前往[CloudFlare Workers](https://workers.cloudflare.com/)官网,注册一个账号,并新建一个Worker +2. 在脚本中写入以下代码 +``:你的机器人token +``` +const whitelist = ["/bot"]; +const tg_host = "api.telegram.org"; + +addEventListener('fetch', event => { + event.respondWith(handleRequest(event.request)) +}) + +function validate(path) { + for (var i = 0; i < whitelist.length; i++) { + if (path.startsWith(whitelist[i])) + return true; + } + return false; +} + +async function handleRequest(request) { + var u = new URL(request.url); + u.host = tg_host; + if (!validate(u.pathname)) + return new Response('Unauthorized', { + status: 403 + }); + var req = new Request(u, { + method: request.method, + headers: request.headers, + body: request.body + }); + const result = await fetch(req); + return result; +} +``` +3. 点击保存并部署 +4. 在将配置文件中的`BotAPILink`修改为这个Worker的地址即可 \ No newline at end of file diff --git a/docs/Telegram/ReverseProxyAPI.md b/docs/Telegram/ReverseProxyAPI.md new file mode 100644 index 0000000..6233cea --- /dev/null +++ b/docs/Telegram/ReverseProxyAPI.md @@ -0,0 +1,40 @@ +中文 | [English](ReverseProxyAPI-en-US.md) | [日本語](ReverseProxyAPI-ja-JP.md) +# TelegramBotAPI反向代理服务器搭建 +*本篇教程将告诉你如何使用CloudFlare Workers搭建一个自己的TelegramBotAPI反向代理服务器* +1. 前往[CloudFlare Workers](https://workers.cloudflare.com/)官网,注册一个账号,并新建一个Worker +2. 在脚本中写入以下代码 +``:你的机器人token +``` +const whitelist = ["/bot"]; +const tg_host = "api.telegram.org"; + +addEventListener('fetch', event => { + event.respondWith(handleRequest(event.request)) +}) + +function validate(path) { + for (var i = 0; i < whitelist.length; i++) { + if (path.startsWith(whitelist[i])) + return true; + } + return false; +} + +async function handleRequest(request) { + var u = new URL(request.url); + u.host = tg_host; + if (!validate(u.pathname)) + return new Response('Unauthorized', { + status: 403 + }); + var req = new Request(u, { + method: request.method, + headers: request.headers, + body: request.body + }); + const result = await fetch(req); + return result; +} +``` +3. 点击保存并部署 +4. 在将配置文件中的`BotAPILink`修改为这个Worker的地址即可 \ No newline at end of file diff --git a/main.go b/main.go index f64826c..8f7ea61 100644 --- a/main.go +++ b/main.go @@ -8,7 +8,7 @@ import ( "github.com/gin-gonic/gin" "xyz.nyan/MediaWiki-Bot/src/InformationProcessing" - "xyz.nyan/MediaWiki-Bot/src/MessageProcessingAPI/SNSAPI/QQAPI" + "xyz.nyan/MediaWiki-Bot/src/MessagePushAPI/SNSAPI/QQAPI" "xyz.nyan/MediaWiki-Bot/src/Struct" "xyz.nyan/MediaWiki-Bot/src/utils" "xyz.nyan/MediaWiki-Bot/src/utils/Language" @@ -16,7 +16,7 @@ import ( ) func Error() { - fmt.Printf(Language.Message("").MainErrorTips) + fmt.Printf(Language.Message("","").MainErrorTips) key := make([]byte, 1) os.Stdin.Read(key) os.Exit(1) @@ -30,10 +30,10 @@ func CycleGetKey() { time.Sleep(299 * time.Second) _, resp, err := QQAPI.CreateSessionKey() if err != nil { - fmt.Println(Language.Message("").UnableApplySession) + fmt.Println(Language.Message("","").UnableApplySession) fmt.Println(err) } else if resp.Status != "200 OK" { - fmt.Println(Language.Message("").UnableApplySession) + fmt.Println(Language.Message("","").UnableApplySession) } } } @@ -48,10 +48,10 @@ func main() { //缓存mirai-api-http Session并启动定时获取进程 _, resp, err := QQAPI.CreateSessionKey() if err != nil { - fmt.Println(Language.Message("").CannotConnectMirai) + fmt.Println(Language.Message("","").CannotConnectMirai) Error() } else if resp.Status != "200 OK" { - fmt.Println(Language.Message("").CannotConnectMirai) + fmt.Println(Language.Message("","").CannotConnectMirai) Error() } go CycleGetKey() @@ -60,7 +60,7 @@ func main() { gin.SetMode(gin.ReleaseMode) r := gin.Default() Port := Config.Run.WebHookPort - fmt.Println(Language.StringVariable(1, Language.Message("").RunOK, Port, "")) + fmt.Println(Language.StringVariable(1, Language.Message("","").RunOK, Port, "")) r.POST("/", func(c *gin.Context) { var json Struct.WebHookJson if err := c.ShouldBindJSON(&json); err != nil { diff --git a/src/InformationProcessing/InformationProcessing.go b/src/InformationProcessing/InformationProcessing.go index c6cbf50..fec5311 100644 --- a/src/InformationProcessing/InformationProcessing.go +++ b/src/InformationProcessing/InformationProcessing.go @@ -5,5 +5,12 @@ import ( ) func InformationProcessing(json Struct.WebHookJson) { - QQMessageProcessing(json) + if json.Type != "" { + QQMessageProcessing(json) + return + } + + if json.Update_id != 0 { + TelegramMessageProcessing(json) + } } \ No newline at end of file diff --git a/src/InformationProcessing/PublicFunc.go b/src/InformationProcessing/PublicFunc.go index 964d7ab..568fb88 100644 --- a/src/InformationProcessing/PublicFunc.go +++ b/src/InformationProcessing/PublicFunc.go @@ -5,10 +5,16 @@ import ( "xyz.nyan/MediaWiki-Bot/src/Struct" "xyz.nyan/MediaWiki-Bot/src/utils" + "xyz.nyan/MediaWiki-Bot/src/utils/Language" ) +//Wiki链接错误返回 +func Error(SNSName string, UserID string, WikiLink string) string { + return Language.StringVariable(1, Language.Message(SNSName, UserID).WikiLinkError, WikiLink, "") +} + //命令处理,判断命令是否匹配,匹配则输出命令和命令参数 -func CommandExtraction(SNSName string, QQjson Struct.WebHookJson, text string) (bool, string, string) { +func CommandExtraction(SNSName string, json Struct.WebHookJson, text string) (bool, string, string) { if find := strings.Contains(text, ":"); find { Config := utils.ReadConfig() var ConfigWikiName string @@ -34,10 +40,12 @@ func CommandExtraction(SNSName string, QQjson Struct.WebHookJson, text string) ( } else if find := strings.Contains(text, "/"); find { switch SNSName { case "QQ": - QQSettingsMessageProcessing(QQjson) + QQSettingsMessageProcessing(json) + case "Telegram": + TelegramSettingsMessageProcessing(json) } return false, "", "/" } return false, "", "" -} \ No newline at end of file +} diff --git a/src/InformationProcessing/QQMessageProcessing.go b/src/InformationProcessing/QQMessageProcessing.go index 67f61d6..aaa1b7e 100644 --- a/src/InformationProcessing/QQMessageProcessing.go +++ b/src/InformationProcessing/QQMessageProcessing.go @@ -6,63 +6,61 @@ import ( "strings" "xyz.nyan/MediaWiki-Bot/src/MediaWikiAPI" - "xyz.nyan/MediaWiki-Bot/src/MessageProcessingAPI" + "xyz.nyan/MediaWiki-Bot/src/MessagePushAPI" "xyz.nyan/MediaWiki-Bot/src/Plugin" + "xyz.nyan/MediaWiki-Bot/src/Plugin/Command" "xyz.nyan/MediaWiki-Bot/src/Struct" "xyz.nyan/MediaWiki-Bot/src/utils" "xyz.nyan/MediaWiki-Bot/src/utils/Language" - "xyz.nyan/MediaWiki-Bot/src/utils/Settings" ) -func QQError(UserID string, WikiLink string) string { - return Language.StringVariable(1, Language.Message(UserID).WikiLinkError, WikiLink, "") -} +var sns_name_qq string = "QQ" //发送群组消息 func QQsendGroupWikiInfo(UserID int, WikiName string, GroupID int, QueryText string, quoteID int) { - WikiInfo, err := Plugin.GetWikiInfo(UserID, WikiName, QueryText) + WikiInfo, err := Plugin.GetWikiInfo(sns_name_qq, UserID, WikiName, QueryText) if err != nil { WikiLink := MediaWikiAPI.GetWikiLink(WikiName) - MessageProcessingAPI.SendGroupMessage("QQ", GroupID, QQError(strconv.Itoa(UserID), WikiLink), true, quoteID) + MessagePushAPI.SendMessage(sns_name_qq, "Group", GroupID, Error(sns_name_qq, strconv.Itoa(UserID), WikiLink), true, quoteID, "", 0) return } - MessageProcessingAPI.SendGroupMessage("QQ", GroupID, WikiInfo, true, quoteID) + MessagePushAPI.SendMessage(sns_name_qq, "Group", GroupID, WikiInfo, true, quoteID, "", 0) } //发送好友消息 func QQsendFriendWikiInfo(WikiName string, UserID int, QueryText string) { - WikiInfo, err := Plugin.GetWikiInfo(UserID, WikiName, QueryText) + WikiInfo, err := Plugin.GetWikiInfo(sns_name_qq, UserID, WikiName, QueryText) if err != nil { WikiLink := MediaWikiAPI.GetWikiLink(WikiName) - MessageProcessingAPI.SendFriendMessage("QQ", UserID, QQError(strconv.Itoa(UserID), WikiLink), false, 0) + MessagePushAPI.SendMessage(sns_name_qq, "Friend", UserID, Error(sns_name_qq, strconv.Itoa(UserID), WikiLink), false, 0, "", 0) return } - MessageProcessingAPI.SendFriendMessage("QQ", UserID, WikiInfo, false, 0) + MessagePushAPI.SendMessage(sns_name_qq, "Friend", UserID, WikiInfo, false, 0, "", 0) } //发送临时会话消息 func QQsendTempdWikiInfo(WikiName string, UserID int, GroupID int, QueryText string) { - WikiInfo, err := Plugin.GetWikiInfo(UserID, WikiName, QueryText) + WikiInfo, err := Plugin.GetWikiInfo(sns_name_qq, UserID, WikiName, QueryText) if err != nil { WikiLink := MediaWikiAPI.GetWikiLink(WikiName) - MessageProcessingAPI.SendTempMessage("QQ", UserID, GroupID, QQError(strconv.Itoa(UserID), WikiLink), false, 0) + MessagePushAPI.SendMessage(sns_name_qq, "Temp", UserID, Error(sns_name_qq, strconv.Itoa(UserID), WikiLink), false, 0, "", GroupID) return } - MessageProcessingAPI.SendTempMessage("QQ", UserID, GroupID, WikiInfo, false, 0) + MessagePushAPI.SendMessage(sns_name_qq, "Temp", UserID, WikiInfo, false, 0, "", GroupID) } //戳一戳消息处理 func QQNudgeEventMessageProcessing(json Struct.WebHookJson) { UserID := json.Sender.Id - HelpText := Language.Message(strconv.Itoa(UserID)).HelpText + HelpText := Language.Message(sns_name_qq, strconv.Itoa(UserID)).HelpText switch json.Subject.Kind { case "Group": - if json.FromId != utils.ReadConfig().QQBot.BotQQNumber && json.Target == utils.ReadConfig().QQBot.BotQQNumber { - go MessageProcessingAPI.SendNudge(json.FromId, json.Subject.Id, "Group") - go MessageProcessingAPI.SendGroupAtMessage("QQ", json.Subject.Id, HelpText, json.FromId) + if json.FromId != utils.ReadConfig().SNS.QQ.BotQQNumber && json.Target == utils.ReadConfig().SNS.QQ.BotQQNumber { + go MessagePushAPI.SendNudge(json.FromId, json.Subject.Id, "Group") + go MessagePushAPI.SendMessage(sns_name_qq, "GroupAt", json.Subject.Id, HelpText, false, 0, strconv.Itoa(json.FromId), 0) } case "Friend": - go MessageProcessingAPI.SendFriendMessage("QQ", json.FromId, HelpText, false, 0) + go MessagePushAPI.SendMessage(sns_name_qq, "Friend", json.FromId, HelpText, false, 0, "", 0) } } @@ -72,19 +70,19 @@ func QQMessageProcessing(json Struct.WebHookJson) { case "GroupMessage": if json.MessageChain[1].(map[string]interface{})["type"] == "Plain" { text := json.MessageChain[1].(map[string]interface{})["text"] - find, QueryText, Command := CommandExtraction("QQ", json, text.(string)) + find, QueryText, Command := CommandExtraction(sns_name_qq, json, text.(string)) if find { GroupID := json.Sender.Group.Id quoteID := int(math.Floor(json.MessageChain[0].(map[string]interface{})["id"].(float64))) UserID := json.Sender.Id - go MessageProcessingAPI.SendNudge(UserID, GroupID, "Group") + go MessagePushAPI.SendNudge(UserID, GroupID, "Group") go QQsendGroupWikiInfo(UserID, Command, GroupID, QueryText, quoteID) } } case "FriendMessage": if json.MessageChain[1].(map[string]interface{})["type"] == "Plain" { text := json.MessageChain[1].(map[string]interface{})["text"] - find, QueryText, Command := CommandExtraction("QQ", json, text.(string)) + find, QueryText, Command := CommandExtraction(sns_name_qq, json, text.(string)) if find { UserID := json.Sender.Id go QQsendFriendWikiInfo(Command, UserID, QueryText) @@ -93,7 +91,7 @@ func QQMessageProcessing(json Struct.WebHookJson) { case "TempMessage": if json.MessageChain[1].(map[string]interface{})["type"] == "Plain" { text := json.MessageChain[1].(map[string]interface{})["text"] - find, QueryText, Command := CommandExtraction("QQ", json, text.(string)) + find, QueryText, Command := CommandExtraction(sns_name_qq, json, text.(string)) if find { UserID := json.Sender.Id GroupID := json.Sender.Group.Id @@ -110,20 +108,20 @@ func QQSettingsMessageProcessing(json Struct.WebHookJson) { text := json.MessageChain[1].(map[string]interface{})["text"] countSplit := strings.Split(text.(string), "/") Text := countSplit[1] - Message, Bool := Settings.Settings("QQ", json, Text) + Message, Bool := Command.Command(sns_name_qq, json, Text) if Bool { switch json.Type { case "GroupMessage": GroupID := json.Sender.Group.Id quoteID := int(math.Floor(json.MessageChain[0].(map[string]interface{})["id"].(float64))) - go MessageProcessingAPI.SendGroupMessage("QQ", GroupID, Message, true, quoteID) + go MessagePushAPI.SendMessage(sns_name_qq, "Group", GroupID, Message, true, quoteID, "", 0) case "FriendMessage": UserID := json.Sender.Id - go MessageProcessingAPI.SendFriendMessage("QQ", UserID, Message, false, 0) + go MessagePushAPI.SendMessage(sns_name_qq, "Friend", UserID, Message, false, 0, "", 0) case "TempMessage": UserID := json.Sender.Id GroupID := json.Sender.Group.Id - go MessageProcessingAPI.SendTempMessage("QQ", UserID, GroupID, Message, false, 0) + go MessagePushAPI.SendMessage(sns_name_qq, "Temp", UserID, Message, false, 0, "", GroupID) } } } diff --git a/src/InformationProcessing/TelegramMessageProcessing.go b/src/InformationProcessing/TelegramMessageProcessing.go new file mode 100644 index 0000000..1353317 --- /dev/null +++ b/src/InformationProcessing/TelegramMessageProcessing.go @@ -0,0 +1,54 @@ +package InformationProcessing + +import ( + "strconv" + "strings" + + "xyz.nyan/MediaWiki-Bot/src/MediaWikiAPI" + "xyz.nyan/MediaWiki-Bot/src/MessagePushAPI" + "xyz.nyan/MediaWiki-Bot/src/Plugin" + "xyz.nyan/MediaWiki-Bot/src/Plugin/Command" + "xyz.nyan/MediaWiki-Bot/src/Struct" +) + +var sns_name_telegram string = "Telegram" + +func TelegramMessageProcessing(json Struct.WebHookJson) { + text := json.Message.Text + find, QueryText, Command := CommandExtraction(sns_name_telegram, json, text) + if find { + UserID := json.Message.From.Id + ChatID := json.Message.Chat.Id + WikiInfo, err := Plugin.GetWikiInfo(sns_name_telegram,UserID, Command, QueryText) + if err != nil { + WikiLink := MediaWikiAPI.GetWikiLink(Command) + go MessagePushAPI.SendMessage(sns_name_telegram, "Default", ChatID, Error(sns_name_telegram,strconv.Itoa(UserID), WikiLink), false, 0, "", 0) + return + } + switch json.Message.Chat.Type { + case "private": + go MessagePushAPI.SendMessage(sns_name_telegram, "Default", ChatID, WikiInfo, false, 0, "", 0) + case "supergroup": + MassageID := json.Message.Message_id + go MessagePushAPI.SendMessage(sns_name_telegram, "Group", ChatID, WikiInfo, true, MassageID, "", 0) + } + } +} + +//设置消息返回 +func TelegramSettingsMessageProcessing(json Struct.WebHookJson) { + text := json.Message.Text + countSplit := strings.Split(text, "/") + Text := countSplit[1] + Message, Bool := Command.Command(sns_name_telegram, json, Text) + if Bool { + ChatID := json.Message.Chat.Id + switch json.Message.Chat.Type { + case "private": + MessagePushAPI.SendMessage(sns_name_telegram, "Default", ChatID, Message, false, 0, "", 0) + case "supergroup": + MassageID := json.Message.Message_id + MessagePushAPI.SendMessage(sns_name_telegram, "Group", ChatID, Message, true, MassageID, "", 0) + } + } +} diff --git a/src/MessageProcessingAPI/SendMessage.go b/src/MessageProcessingAPI/SendMessage.go deleted file mode 100644 index 2b41a55..0000000 --- a/src/MessageProcessingAPI/SendMessage.go +++ /dev/null @@ -1,65 +0,0 @@ -package MessageProcessingAPI - -import ( - "xyz.nyan/MediaWiki-Bot/src/MessageProcessingAPI/SNSAPI/QQAPI" -) - -//发送好友消息 -//SNSName 聊天软件 -//target 好友ID -//text 消息文本 -//quote 是否需要回复 -//quoteID 回复的消息ID(不需要时为0即可) -func SendFriendMessage(SNSName string, target int, text string, quote bool, quoteID int) { - switch SNSName { - case "QQ": - QQAPI.SendFriendMessage(target, text, quote, quoteID) - } -} - -//发送群消息 -//SNSName 聊天软件 -//target 群号 -//text 消息文本 -//quote 是否需要回复 -//quoteID 回复的消息ID(不需要时为0即可) -func SendGroupMessage(SNSName string, target int, text string, quote bool, quoteID int) { - switch SNSName { - case "QQ": - QQAPI.SendGroupMessage(target, text, quote, quoteID) - } -} - -//发送带@的群消息 -//SNSName 聊天软件 -//target 群号 -//text 消息文本 -//AtID 需要@的人的ID -func SendGroupAtMessage(SNSName string, target int, text string, AtID int) { - switch SNSName { - case "QQ": - QQAPI.SendGroupAtMessage(target, text, AtID) - } -} - -//发送陌生人会话 -//SNSName 聊天软件 -//target 陌生人对象ID -//group 临时会话群号 -//text 消息文本 -//quote 是否需要回复 -//quoteID 回复的消息ID(不需要时为0即可) -func SendTempMessage(SNSName string, target int, group int, text string, quote bool, quoteID int) { - switch SNSName { - case "QQ": - QQAPI.SendTempMessage(target, group, text, quote, quoteID) - } -} - -//(QQ)发送头像戳一戳 -//target 目标QQ号 -//subject 消息接受主体,为群号或QQ号 -//kind 上下文类型,可选值 Friend,Group,Stranger -func SendNudge(target int, subject int, kind string) { - QQAPI.SendNudge(target, subject, kind) -} diff --git a/src/MessageProcessingAPI/SNSAPI/QQAPI/QQAPI.go b/src/MessagePushAPI/SNSAPI/QQAPI/QQAPI.go similarity index 81% rename from src/MessageProcessingAPI/SNSAPI/QQAPI/QQAPI.go rename to src/MessagePushAPI/SNSAPI/QQAPI/QQAPI.go index 5188c00..af0092a 100644 --- a/src/MessageProcessingAPI/SNSAPI/QQAPI/QQAPI.go +++ b/src/MessagePushAPI/SNSAPI/QQAPI/QQAPI.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" "strconv" - "time" + "xyz.nyan/MediaWiki-Bot/src/MessagePushAPI/SNSAPI" "xyz.nyan/MediaWiki-Bot/src/utils" "xyz.nyan/MediaWiki-Bot/src/utils/Language" ) @@ -16,19 +16,21 @@ type returnJson struct { MessageId string `json:"messageId"` } +var sns_name string = "QQ" + func sendError(body []byte, err error, url string, requestBody string) { if err != nil { - fmt.Println(Language.Message("").CannotConnectMirai) + fmt.Println(Language.Message("", "").CannotConnectMirai) } else { var config returnJson json.Unmarshal([]byte(body), &config) if config.Code != 0 { SessionKey, resp, err := CreateSessionKey() if err != nil { - fmt.Println(Language.Message("").CannotConnectMirai) + fmt.Println(Language.Message("", "").CannotConnectMirai) fmt.Println(err) } else if resp.Status != "200 OK" { - fmt.Println(Language.Message("").CannotConnectMirai) + fmt.Println(Language.Message("", "").CannotConnectMirai) } else { var result map[string]interface{} json.Unmarshal([]byte(requestBody), &result) @@ -40,17 +42,6 @@ func sendError(body []byte, err error, url string, requestBody string) { } } -//日志输出 -//Type 消息类型,可选 Friend,Group,Stranger -//target 消息来源 -//text 消息主体 -func log(Type string, target string, text string) { - timestamp := time.Now().Unix() - tm := time.Unix(timestamp, 0) - - fmt.Println("[" + tm.Format("2006-01-02 03:04:05") + "] [" + Type + "] " + target + " -> " + text) -} - //发送群消息 //target 群号 //text 消息文本 @@ -86,11 +77,11 @@ func SendGroupMessage(target int, text string, quote bool, quoteID int) { }`, sessionKey, target, text) } - url := Config.QQBot.APILink + "/sendGroupMessage" + url := Config.SNS.QQ.APILink + "/sendGroupMessage" body, _, err := utils.PostRequestJosn(url, requestBody) sendError(body, err, url, requestBody) - log("Group", strconv.Itoa(target), text) + SNSAPI.Log(sns_name, "Group", strconv.Itoa(target), text) } //发送带@的群消息 @@ -115,11 +106,11 @@ func SendGroupAtMessage(target int, text string, AtID int) { } ] }`, sessionKey, target, AtID, text) - url := Config.QQBot.APILink + "/sendGroupMessage" + url := Config.SNS.QQ.APILink + "/sendGroupMessage" body, _, err := utils.PostRequestJosn(url, requestBody) sendError(body, err, url, requestBody) - log("Group", strconv.Itoa(target), text) + SNSAPI.Log(sns_name, "Group", strconv.Itoa(target), text) } //发送头像戳一戳 @@ -136,11 +127,11 @@ func SendNudge(target int, subject int, kind string) { "kind":"%s" }`, sessionKey, target, subject, kind) - url := Config.QQBot.APILink + "/sendNudge" + url := Config.SNS.QQ.APILink + "/sendNudge" body, _, err := utils.PostRequestJosn(url, requestBody) sendError(body, err, url, requestBody) - log(kind, strconv.Itoa(subject), Language.Message("").Nudge+strconv.Itoa(target)) + SNSAPI.Log(sns_name, kind, strconv.Itoa(subject), Language.Message("", "").Nudge+strconv.Itoa(target)) } //发送好友消息 @@ -178,11 +169,11 @@ func SendFriendMessage(target int, text string, quote bool, quoteID int) { }`, sessionKey, target, text) } - url := Config.QQBot.APILink + "/sendFriendMessage" + url := Config.SNS.QQ.APILink + "/sendFriendMessage" body, _, err := utils.PostRequestJosn(url, requestBody) sendError(body, err, url, requestBody) - log("Friend", strconv.Itoa(target), text) + SNSAPI.Log(sns_name, "Friend", strconv.Itoa(target), text) } //发送临时会话 @@ -223,9 +214,9 @@ func SendTempMessage(target int, group int, text string, quote bool, quoteID int }`, sessionKey, target, group, text) } - url := Config.QQBot.APILink + "/sendTempMessage" + url := Config.SNS.QQ.APILink + "/sendTempMessage" body, _, err := utils.PostRequestJosn(url, requestBody) sendError(body, err, url, requestBody) - log("Temp", strconv.Itoa(target), text) + SNSAPI.Log(sns_name, "Temp", strconv.Itoa(target), text) } diff --git a/src/MessageProcessingAPI/SNSAPI/QQAPI/SessionKey.go b/src/MessagePushAPI/SNSAPI/QQAPI/SessionKey.go similarity index 82% rename from src/MessageProcessingAPI/SNSAPI/QQAPI/SessionKey.go rename to src/MessagePushAPI/SNSAPI/QQAPI/SessionKey.go index a878c43..84fd767 100644 --- a/src/MessageProcessingAPI/SNSAPI/QQAPI/SessionKey.go +++ b/src/MessagePushAPI/SNSAPI/QQAPI/SessionKey.go @@ -22,16 +22,16 @@ func CreateSessionKey() (string, *http.Response, error) { requestBody := fmt.Sprintf(`{ "verifyKey": "%s", "qq": %d - }`, OldSessionKey, Config.QQBot.BotQQNumber) - url := Config.QQBot.APILink + "/release" + }`, OldSessionKey, Config.SNS.QQ.BotQQNumber) + url := Config.SNS.QQ.APILink + "/release" utils.PostRequestJosn(url, requestBody) var SessionKey string Config = utils.ReadConfig() requestBody = fmt.Sprintf(`{ "verifyKey": "%s" - }`, Config.QQBot.VerifyKey) - url = Config.QQBot.APILink + "/verify" + }`, Config.SNS.QQ.VerifyKey) + url = Config.SNS.QQ.APILink + "/verify" body, resp, http_error := utils.PostRequestJosn(url, requestBody) var config verifyJson @@ -42,8 +42,8 @@ func CreateSessionKey() (string, *http.Response, error) { requestBody = fmt.Sprintf(`{ "sessionKey": "%s", "qq": %d - }`, SessionKey, Config.QQBot.BotQQNumber) - url = Config.QQBot.APILink + "/bind" + }`, SessionKey, Config.SNS.QQ.BotQQNumber) + url = Config.SNS.QQ.APILink + "/bind" utils.PostRequestJosn(url, requestBody) //缓存SessionKey diff --git a/src/MessagePushAPI/SNSAPI/SNSAPI.go b/src/MessagePushAPI/SNSAPI/SNSAPI.go new file mode 100644 index 0000000..5f2194a --- /dev/null +++ b/src/MessagePushAPI/SNSAPI/SNSAPI.go @@ -0,0 +1,18 @@ +package SNSAPI + +import ( + "fmt" + "time" +) + +//日志输出 +//SNSName 聊天软件名字 +//Type 消息类型,可选 Friend,Group,Stranger +//target 消息接收者 +//text 消息主体 +func Log(SNSName string, Type string, target string, text string) { + timestamp := time.Now().Unix() + tm := time.Unix(timestamp, 0) + + fmt.Println("[" + tm.Format("2006-01-02 03:04:05") + "] [" + SNSName + "] [" + Type + "] " + target + " -> " + text) +} diff --git a/src/MessagePushAPI/SNSAPI/TelegramAPI/TelegramAPI.go b/src/MessagePushAPI/SNSAPI/TelegramAPI/TelegramAPI.go new file mode 100644 index 0000000..fcd676c --- /dev/null +++ b/src/MessagePushAPI/SNSAPI/TelegramAPI/TelegramAPI.go @@ -0,0 +1,35 @@ +package TelegramAPI + +import ( + "fmt" + "strconv" + + "xyz.nyan/MediaWiki-Bot/src/MessagePushAPI/SNSAPI" + "xyz.nyan/MediaWiki-Bot/src/utils" +) + +var sns_name string = "Telegram" + +//发送消息 +//chat_id 聊天ID +//text 需要发送的信息 +//disable_web_page_preview 是否需要禁用链接预览 +//disable_notification 是否需要静默发送 +//reply_to_message_id 需要回复消息的ID +//allow_sending_without_reply 没有找到需要回复的消息时,是否发送 +func SendMessage(chat_type string, chat_id int, text string, disable_web_page_preview bool, disable_notification bool, reply_to_message_id int, allow_sending_without_reply bool) { + Config := utils.ReadConfig() + requestBody := fmt.Sprintf(`{ + "chat_id": %d, + "text": "%s", + "disable_web_page_preview": %t, + "disable_notification": %t, + "reply_to_message_id": %d, + "allow_sending_without_reply": %t + }`, chat_id, text, disable_web_page_preview, disable_notification, reply_to_message_id, allow_sending_without_reply) + + url := Config.SNS.Telegram.BotAPILink + "bot" + Config.SNS.Telegram.Token + "/sendMessage" + utils.PostRequestJosn(url, requestBody) + + SNSAPI.Log(sns_name, chat_type, strconv.Itoa(chat_id), text) +} diff --git a/src/MessagePushAPI/SendMessage.go b/src/MessagePushAPI/SendMessage.go new file mode 100644 index 0000000..89cf5d3 --- /dev/null +++ b/src/MessagePushAPI/SendMessage.go @@ -0,0 +1,50 @@ +package MessagePushAPI + +import ( + "strconv" + + "xyz.nyan/MediaWiki-Bot/src/MessagePushAPI/SNSAPI/QQAPI" + "xyz.nyan/MediaWiki-Bot/src/MessagePushAPI/SNSAPI/TelegramAPI" +) + +//发送消息 +//SNSName 聊天软件 +//ChatType 聊天类型(Default,Friend,Group,GroupAt,Temp) +//target 接受的聊天的ID +//text 消息文本 +//quote 是否需要回复 +//quoteID 回复的消息ID(不需要时为0即可) +//AtID (可选)需要@的人的ID +//group (可选)临时会话群号 +func SendMessage(SNSName string, ChatType string, target int, text string, quote bool, quoteID int, AtID string, group int) { + switch SNSName { + case "QQ": + switch ChatType { + case "Friend": + QQAPI.SendFriendMessage(target, text, quote, quoteID) + case "Group": + QQAPI.SendGroupMessage(target, text, quote, quoteID) + case "GroupAt": + AtID, _ := strconv.Atoi(AtID) + QQAPI.SendGroupAtMessage(target, text, AtID) + case "Temp": + QQAPI.SendTempMessage(target, group, text, quote, quoteID) + } + case "Telegram": + switch ChatType { + case "GroupAt": + text = "@" + AtID + " " + text + TelegramAPI.SendMessage("Group", target, text, true, false, 0, false) + default: + TelegramAPI.SendMessage("Friend", target, text, true, false, quoteID, quote) + } + } +} + +//(QQ)发送头像戳一戳 +//target 目标QQ号 +//subject 消息接受主体,为群号或QQ号 +//kind 上下文类型,可选值 Friend,Group,Stranger +func SendNudge(target int, subject int, kind string) { + QQAPI.SendNudge(target, subject, kind) +} diff --git a/src/Plugin/Command/Command.go b/src/Plugin/Command/Command.go new file mode 100644 index 0000000..3e3a34a --- /dev/null +++ b/src/Plugin/Command/Command.go @@ -0,0 +1,24 @@ +package Command + +import ( + "strconv" + "strings" + + "xyz.nyan/MediaWiki-Bot/src/Struct" +) + +func Command(SNSName string, Messagejson Struct.WebHookJson, CommandText string) (string, bool) { + if find := strings.Contains(CommandText, "language"); find { + countSplit := strings.SplitN(CommandText, " ", 2) + Language := countSplit[1] + var UserID int + switch SNSName { + case "QQ": + UserID = Messagejson.Sender.Id + case "Telegram": + UserID = Messagejson.Message.From.Id + } + return LanguageSettings(SNSName, strconv.Itoa(UserID), Language) + } + return "", false +} diff --git a/src/Plugin/Command/LanguageSettings.go b/src/Plugin/Command/LanguageSettings.go new file mode 100644 index 0000000..ae8ee18 --- /dev/null +++ b/src/Plugin/Command/LanguageSettings.go @@ -0,0 +1,48 @@ +package Command + +import ( + "xyz.nyan/MediaWiki-Bot/src/Struct" + "xyz.nyan/MediaWiki-Bot/src/utils" + Languages "xyz.nyan/MediaWiki-Bot/src/utils/Language" +) + +func LanguageSettings(SNSName string, UserID string, Language string) (string, bool) { + var MessageOK bool + var Message string + db := utils.SQLLiteLink() + + db.AutoMigrate(&Struct.UserInfo{}) + + var user Struct.UserInfo + db.Where("account = ? and sns_name = ?", UserID, SNSName).Find(&user) + if user.Account != UserID { + files := Languages.LanguageList() + for _, LanguageName := range files { + if LanguageName == Language { + UserInfos := Struct.UserInfo{SNSName: SNSName, Account: UserID, Language: Language} + db.Create(&UserInfos) + MessageOK = true + Message = Languages.StringVariable(1, Languages.Message(SNSName, UserID).LanguageModifiedSuccessfully, LanguageName, "") + break + } else { + MessageOK = true + Message = Languages.StringVariable(1, Languages.Message(SNSName, UserID).LanguageModificationFailed, LanguageName, "") + } + } + } else { + files := Languages.LanguageList() + for _, LanguageName := range files { + if Language == LanguageName { + db.Model(&Struct.UserInfo{}).Where("account = ? and sns_name = ?", UserID, SNSName).Update("language", Language) + MessageOK = true + Message = Languages.StringVariable(1, Languages.Message(SNSName, UserID).LanguageModifiedSuccessfully, LanguageName, "") + break + } else { + MessageOK = true + Message = Languages.StringVariable(1, Languages.Message(SNSName, UserID).LanguageModificationFailed, LanguageName, "") + } + } + } + + return Message, MessageOK +} diff --git a/src/Plugin/GetWikiInfo.go b/src/Plugin/GetWikiInfo.go index f6a40c0..e07afb1 100644 --- a/src/Plugin/GetWikiInfo.go +++ b/src/Plugin/GetWikiInfo.go @@ -11,8 +11,8 @@ import ( "xyz.nyan/MediaWiki-Bot/src/utils/Language" ) -func Error(UserID int, WikiLink string, title string) string { - text := Language.StringVariable(2, Language.Message(strconv.Itoa(UserID)).GetWikiInfoError, WikiLink, title) +func Error(SNSName string, UserID int, WikiLink string, title string) string { + text := Language.StringVariable(2, Language.Message(SNSName, strconv.Itoa(UserID)).GetWikiInfoError, WikiLink, title) return text } @@ -37,14 +37,14 @@ func SearchWiki(WikiName string, title string) string { } //为空处理 -func NilProcessing(UserID int, WikiName string, title string) string { +func NilProcessing(SNSName string, UserID int, WikiName string, title string) string { SearchInfo := SearchWiki(WikiName, title) if SearchInfo != "" { - Info := Language.StringVariable(2, Language.Message(strconv.Itoa(UserID)).WikiInfoSearch, SearchInfo, WikiName) + Info := Language.StringVariable(2, Language.Message(SNSName, strconv.Itoa(UserID)).WikiInfoSearch, SearchInfo, WikiName) return Info } else { WikiLink := MediaWikiAPI.GetWikiLink(WikiName) - return Error(UserID, WikiLink, title) + return Error(SNSName, UserID, WikiLink, title) } } @@ -98,7 +98,7 @@ func QueryRedirects(WikiName string, title string) (whether bool, to string, fro } //获取Wiki页面信息 -func GetWikiInfo(UserID int, WikiName string, title string) (string, error) { +func GetWikiInfo(SNSName string, UserID int, WikiName string, title string) (string, error) { var err error RedirectsState, ToTitle, FromTitle, _ := QueryRedirects(WikiName, title) var info map[string]interface{} @@ -110,12 +110,12 @@ func GetWikiInfo(UserID int, WikiName string, title string) (string, error) { _, ok := info["query"] if !ok { - return NilProcessing(UserID, WikiName, title), err + return NilProcessing(SNSName, UserID, WikiName, title), err } pagesIdInfo, ok := info["query"].(map[string]interface{})["pages"] if !ok { - return NilProcessing(UserID, WikiName, title), err + return NilProcessing(SNSName, UserID, WikiName, title), err } var PageId string @@ -132,7 +132,7 @@ func GetWikiInfo(UserID int, WikiName string, title string) (string, error) { log.Println(err) } WikiPageLink := WikiPageInfo.(map[string]interface{})["fullurl"].(string) - info := Language.StringVariable(2, Language.Message(strconv.Itoa(UserID)).WikiInfoRedirect, FromTitle, ToTitle) + info := Language.StringVariable(2, Language.Message(SNSName, strconv.Itoa(UserID)).WikiInfoRedirect, FromTitle, ToTitle) returnText = WikiPageLink + info + PagesExtract.(string) } else { WikiPageInfo, err := QueryWikiInfo(WikiName, title) @@ -144,6 +144,6 @@ func GetWikiInfo(UserID int, WikiName string, title string) (string, error) { } return returnText, err } else { - return NilProcessing(UserID, WikiName, title), err + return NilProcessing(SNSName, UserID, WikiName, title), err } } diff --git a/src/Struct/SQL.go b/src/Struct/SQL.go index e398a26..42a5301 100644 --- a/src/Struct/SQL.go +++ b/src/Struct/SQL.go @@ -1,7 +1,8 @@ package Struct -type QQUserInfo struct { +type UserInfo struct { Id int `gorm:"primary_key"` + SNSName string `gorm:"sns_name"` Account string `gorm:"type:varchar(255);not null;index:account"` Language string `gorm:"type:varchar(255);index:language"` -} \ No newline at end of file +} diff --git a/src/Struct/WebHook.go b/src/Struct/WebHook.go index aff77be..04f0428 100644 --- a/src/Struct/WebHook.go +++ b/src/Struct/WebHook.go @@ -1,13 +1,20 @@ package Struct type WebHookJson struct { + //QQ Type string `json:"type"` Sender Sender `json:"sender"` FromId int `json:"fromId"` Target int `json:"target"` MessageChain []interface{} `json:"messageChain"` Subject Subject `json:"subject"` + + //Telegram + Update_id int `json:"update_id"` + Message Message `json:"message"` } + +//QQ type Sender struct { Id int `json:"id"` MemberName string `json:"memberName"` @@ -28,3 +35,28 @@ type Subject struct { Id int `json:"id"` Kind string `json:"kind"` } + +//Telegram +type Message struct { + Message_id int `json:"message_id"` + From From `json:"from"` + Chat Chat `json:"chat"` + Date int `json:"date"` + Text string `json:"text"` +} +type From struct { + Id int `json:"id"` + Is_bot bool `json:"is_bot"` + First_name string `json:"first_name"` + Last_name string `json:"last_name"` + Username string `json:"username"` + Language_code string `json:"language_code"` +} +type Chat struct { + Id int `json:"id"` + Title string `json:"title"` + First_name string `json:"first_name"` + Last_name string `json:"last_name"` + Username string `json:"username"` + Type string `json:"type"` +} diff --git a/src/utils/Language/Language.go b/src/utils/Language/Language.go index e56a0da..42ec279 100644 --- a/src/utils/Language/Language.go +++ b/src/utils/Language/Language.go @@ -49,16 +49,16 @@ func StringVariable(quantity int, strHaiCoder string, text0 string, text1 string return text } -//使用默认语言Account为空即可 -func Message(Account string) *LanguageInfo { +//使用默认语言参数都为空即可 +func Message(SNSName string, Account string) *LanguageInfo { var language string if Account == "" { Config := utils.ReadConfig() language = Config.Run.Language } else { db := utils.SQLLiteLink() - var user Struct.QQUserInfo - db.Where("account = ?", Account).Find(&user) + var user Struct.UserInfo + db.Where("account = ? and sns_name = ?", Account, SNSName).Find(&user) if user.Language != "" { language = user.Language } else { diff --git a/src/utils/ReadConfig.go b/src/utils/ReadConfig.go index 6499de7..28a837d 100644 --- a/src/utils/ReadConfig.go +++ b/src/utils/ReadConfig.go @@ -7,30 +7,38 @@ import ( ) type Config struct { - Run *Run `yaml:"Run"` - QQBot *QQBot `yaml:"QQBot"` + Run *Run `yaml:"Run"` + SNS *SNS `yaml:"SNS"` Wiki interface{} `yaml:"Wiki"` } type Run struct { WebHookPort string `yaml:"WebHookPort"` - Language string `yaml:"Language"` + Language string `yaml:"Language"` } -type QQBot struct { - APILink string `yaml:"APILink"` - BotQQNumber int `yaml:"BotQQNumber"` - VerifyKey string `yaml:"VerifyKey"` +type SNS struct { + QQ *QQ `yaml:"QQ"` + Telegram *Telegram `yaml:"Telegram"` +} +type QQ struct { + APILink string `yaml:"APILink"` + BotQQNumber int `yaml:"BotQQNumber"` + VerifyKey string `yaml:"VerifyKey"` +} +type Telegram struct { + Token string `yaml:"Token"` + BotAPILink string `yaml:"BotAPILink"` } -func ReadConfig() (*Config) { - content,err := ioutil.ReadFile("./config.yml") - if err != nil{ +func ReadConfig() *Config { + content, err := ioutil.ReadFile("./config.yml") + if err != nil { panic(err) } newStu := &Config{} - err = yaml.Unmarshal(content,&newStu) - if err != nil{ + err = yaml.Unmarshal(content, &newStu) + if err != nil { panic(err) } return newStu @@ -39,4 +47,4 @@ func ReadConfig() (*Config) { func CheckConfigFile() bool { _, err := os.Lstat("./config.yml") return os.IsNotExist(err) -} \ No newline at end of file +} diff --git a/src/utils/Settings/LanguageSettings.go b/src/utils/Settings/LanguageSettings.go deleted file mode 100644 index 9e2f92f..0000000 --- a/src/utils/Settings/LanguageSettings.go +++ /dev/null @@ -1,48 +0,0 @@ -package Settings - -import ( - "xyz.nyan/MediaWiki-Bot/src/Struct" - "xyz.nyan/MediaWiki-Bot/src/utils" - Languages "xyz.nyan/MediaWiki-Bot/src/utils/Language" -) - -func LanguageSettings(UserID string, Language string) (string, bool) { - var MessageOK bool - var Message string - db := utils.SQLLiteLink() - - db.AutoMigrate(&Struct.QQUserInfo{}) - - var user Struct.QQUserInfo - db.Where("account = ?", UserID).Find(&user) - if user.Account != UserID { - files := Languages.LanguageList() - for _, LanguageName := range files { - if LanguageName == Language { - UserInfos := Struct.QQUserInfo{Account: UserID, Language: Language} - db.Create(&UserInfos) - MessageOK = true - Message = Languages.StringVariable(1, Languages.Message(UserID).LanguageModifiedSuccessfully, LanguageName, "") - break - } else { - MessageOK = true - Message = Languages.StringVariable(1, Languages.Message(UserID).LanguageModificationFailed, LanguageName, "") - } - } - } else { - files := Languages.LanguageList() - for _, LanguageName := range files { - if Language == LanguageName { - db.Model(&Struct.QQUserInfo{}).Where("account = ?", UserID).Update("language", Language) - MessageOK = true - Message = Languages.StringVariable(1, Languages.Message(UserID).LanguageModifiedSuccessfully, LanguageName, "") - break - } else { - MessageOK = true - Message = Languages.StringVariable(1, Languages.Message(UserID).LanguageModificationFailed, LanguageName, "") - } - } - } - - return Message, MessageOK -} diff --git a/src/utils/Settings/Settings.go b/src/utils/Settings/Settings.go deleted file mode 100644 index 897d432..0000000 --- a/src/utils/Settings/Settings.go +++ /dev/null @@ -1,21 +0,0 @@ -package Settings - -import ( - "strconv" - "strings" - - "xyz.nyan/MediaWiki-Bot/src/Struct" -) - -func Settings(SNSName string, QQMessagejson Struct.WebHookJson, CommandText string) (string, bool) { - if find := strings.Contains(CommandText, "language"); find { - switch SNSName { - case "QQ": - countSplit := strings.SplitN(CommandText, " ", 2) - Language := countSplit[1] - UserID := QQMessagejson.Sender.Id - return LanguageSettings(strconv.Itoa(UserID), Language) - } - } - return "", false -}