-
Notifications
You must be signed in to change notification settings - Fork 2
/
tg2misskey.go
270 lines (254 loc) · 7.75 KB
/
tg2misskey.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package main
import (
"fmt"
"os"
"path/filepath"
"strconv"
"time"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
"github.com/joho/godotenv"
log "github.com/sirupsen/logrus"
mi "github.com/yitsushi/go-misskey"
"github.com/yitsushi/go-misskey/core"
"github.com/yitsushi/go-misskey/models"
"github.com/yitsushi/go-misskey/services/drive/files"
"github.com/yitsushi/go-misskey/services/drive/folders"
"github.com/yitsushi/go-misskey/services/notes"
)
type View struct {
localOnly bool
visibility models.Visibility
}
func main() {
startTime := time.Now()
// 检查配置文件是否存在,如果不存在则直接读取环境变量
if _, err := os.Stat("config.env"); os.IsNotExist(err) {
log.Info("config.env file not found, reading from environment variables")
if os.Getenv("MISSKEY_URL") == "" || os.Getenv("MISSKEY_TOKEN") == "" || os.Getenv("TELEGRAM_BOT_TOKEN") == "" {
log.Fatal("MISSKEY_URL, MISSKEY_TOKEN and TELEGRAM_BOT_TOKEN must be set")
}
} else {
err := godotenv.Load("config.env")
if err != nil {
log.Fatal("Error loading config.env file")
}
}
// misskey
client, err := mi.NewClientWithOptions(mi.WithSimpleConfig(os.Getenv("MISSKEY_URL"), os.Getenv("MISSKEY_TOKEN")))
if err != nil {
log.Fatal(err)
}
// client.LogLevel(log.InfoLevel)
var v View
if os.Getenv("LOCAL_ONLY") == "true" {
v.localOnly = true
} else if os.Getenv("LOCAL_ONLY") == "false" {
v.localOnly = false
} else {
log.Fatal("LOCAL_ONLY value can only be set to true or false")
}
switch os.Getenv("VISIBILITY") {
case "public":
v.visibility = models.VisibilityPublic
case "home":
v.visibility = models.VisibilityHome
case "followers":
v.visibility = models.VisibilityFollowers
default:
log.Fatal("VISIBILITY value can only be set to public, home or followers")
}
if findFolder(client, os.Getenv("UPLOAD_FOLDER")) == "" {
createFolder(client, os.Getenv("UPLOAD_FOLDER"))
}
// tgbot
bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_BOT_TOKEN"))
if err != nil {
log.Panic(err)
}
log.Info("Authorized on account ", bot.Self.UserName)
var chatId int64
var userId int64
if os.Getenv("TELEGRAM_CHAT_ID") == "" {
chatId = 0
} else {
chatId, err = strconv.ParseInt(os.Getenv("TELEGRAM_CHAT_ID"), 10, 64)
if err != nil {
log.Fatal("Invalid TELEGRAM_CHAT_ID")
}
}
if os.Getenv("TELEGRAM_USER_ID") == "" {
userId = 0
} else {
userId, err = strconv.ParseInt(os.Getenv("TELEGRAM_USER_ID"), 10, 64)
if err != nil {
log.Fatal("Invalid TELEGRAM_USER_ID")
}
}
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updatesChannel := bot.GetUpdatesChan(u)
var fileIDs []string
var msg string
for update := range updatesChannel {
// 只处理启动后,不为空,且来自指定 chatId 或 userId 的消息
if update.Message == nil || update.Message.Time().Before(startTime) {
continue
}
if (chatId != 0 && update.Message.Chat.ID != chatId) || (userId != 0 && update.Message.From.ID != userId) {
continue
}
if update.Message.IsCommand() {
// 处理命令
help := func() {
text := "Hello! I'm a bot that forwards Telegram messages to Misskey.\n\n"
text += "Send me a message or forward a message to me and I'll forward it to Misskey.\n\n"
tgmsg := tgbotapi.NewMessage(update.Message.Chat.ID, text)
tgmsg.ReplyToMessageID = update.Message.MessageID
_, _ = bot.Send(tgmsg)
}
switch update.Message.Command() {
case "start":
help()
case "help":
help()
default:
continue
}
}
if update.Message.Photo != nil {
for i, photo := range update.Message.Photo {
// 只上传最高画质的图片,即 slice 里的最后一个元素
if i == len(update.Message.Photo)-1 {
fileUrl, err := bot.GetFileDirectURL(photo.FileID)
if err != nil {
log.Error(err)
} else {
fillMsgAndFileIDs(client, &fileIDs, &msg, update.Message.Caption, fileUrl)
}
}
}
if len(updatesChannel) == 0 {
addFootInfo(&msg, update.Message)
sendWithAttachment(client, v, &msg, &fileIDs)
}
} else if update.Message.Video != nil {
fileUrl, err := bot.GetFileDirectURL(update.Message.Document.FileID)
if err != nil {
log.Error(err)
continue
}
fillMsgAndFileIDs(client, &fileIDs, &msg, update.Message.Caption, fileUrl)
if len(updatesChannel) == 0 {
addFootInfo(&msg, update.Message)
sendWithAttachment(client, v, &msg, &fileIDs)
}
} else if update.Message.Audio != nil {
fileUrl, err := bot.GetFileDirectURL(update.Message.Document.FileID)
if err != nil {
log.Error(err)
continue
}
fillMsgAndFileIDs(client, &fileIDs, &msg, update.Message.Caption, fileUrl)
if len(updatesChannel) == 0 {
addFootInfo(&msg, update.Message)
sendWithAttachment(client, v, &msg, &fileIDs)
}
} else if update.Message.Document != nil {
fileUrl, err := bot.GetFileDirectURL(update.Message.Document.FileID)
if err != nil {
log.Error(err)
continue
}
fillMsgAndFileIDs(client, &fileIDs, &msg, update.Message.Caption, fileUrl)
if len(updatesChannel) == 0 {
addFootInfo(&msg, update.Message)
sendWithAttachment(client, v, &msg, &fileIDs)
}
} else {
msg = update.Message.Text
addFootInfo(&msg, update.Message)
sendMiNote(client, v, &msg, nil)
}
}
}
func addFootInfo(msg *string, tgMsg *tgbotapi.Message) {
*msg += "\n\n"
if os.Getenv("APPEND_FORWARDED_MESSAGE_SOURCE") == "true" && tgMsg.ForwardFromChat != nil {
*msg += "<small>\n"
if tgMsg.ForwardFromChat.IsChannel() {
if tgMsg.ForwardFromChat.UserName != "" {
*msg += fmt.Sprintf("Forwarded from Telegram Channel \"%s\" `@%s`", tgMsg.ForwardFromChat.Title, tgMsg.ForwardFromChat.UserName)
} else {
*msg += fmt.Sprintf("Forwarded from Telegram Channel \"%s\"", tgMsg.ForwardFromChat.Title)
}
}
if tgMsg.ForwardFromChat.IsGroup() {
*msg += fmt.Sprintf("Forwarded from Telegram Group \"%s\"", tgMsg.ForwardFromChat.Title)
}
}
*msg += fmt.Sprintf("\n*%s*", os.Getenv("FOOT_INFO"))
*msg += "\n</small>"
}
func sendMiNote(client *mi.Client, v View, msg *string, fileIDs []string) {
resp, err := client.Notes().Create(notes.CreateRequest{
Text: core.NewString(*msg),
Visibility: v.visibility,
LocalOnly: v.localOnly,
FileIDs: fileIDs,
})
if err != nil {
log.Errorf("[Notes] Error happened: %s", err)
return
}
log.Infof("Note: %s Created", resp.CreatedNote.ID)
}
func uploadFile(client *mi.Client, fileURL string) string {
file, err := client.Drive().File().CreateFromURL(files.CreateFromURLOptions{
Name: strconv.FormatInt(time.Now().UnixNano(), 10) + filepath.Ext(fileURL),
URL: fileURL,
FolderID: findFolder(client, os.Getenv("UPLOAD_FOLDER")),
})
if err != nil {
log.Errorf("[Drive/File/CreateFromURL] %s", err)
return ""
}
log.Info("File: " + *file.Name + " with ID: " + file.ID + " uploaded")
return file.ID
}
func findFolder(client *mi.Client, name string) string {
folderList, err := client.Drive().Folder().Find(folders.FindRequest{
Name: name,
})
if err != nil {
log.Errorf("[Drive/Folder/Find] %s", err)
return ""
}
for _, folder := range folderList {
if folder.Name == name {
return folder.ID
}
}
return ""
}
func createFolder(client *mi.Client, name string) string {
folder, err := client.Drive().Folder().Create(folders.CreateRequest{
Name: name,
})
if err != nil {
log.Errorf("[Drive/Folder/Create] %s", err)
return ""
}
log.Info("Folder: " + folder.Name + " with ID: " + folder.ID + " created")
return folder.ID
}
func fillMsgAndFileIDs(client *mi.Client, fileIDs *[]string, msg *string, caption string, fileURL string) {
*fileIDs = append(*fileIDs, uploadFile(client, fileURL))
if caption != "" {
*msg = caption
}
}
func sendWithAttachment(client *mi.Client, v View, msg *string, fileIDs *[]string) {
sendMiNote(client, v, msg, *fileIDs)
*fileIDs = nil
*msg = ""
}