This commit is contained in:
shoopea 2019-05-03 12:08:15 +08:00
parent fc52fc66f5
commit d984dc4f7f

314
main.go
View File

@ -1,13 +1,13 @@
package main package main
import ( import (
"fmt" "encoding/json"
"log" "fmt"
"time" "log"
"encoding/json" "time"
"github.com/Arman92/go-tdlib" "github.com/Arman92/go-tdlib"
"github.com/streadway/amqp" "github.com/streadway/amqp"
) )
type MsgDirection int type MsgDirection int
@ -18,190 +18,187 @@ const (
) )
type ChatWarsMessage struct { type ChatWarsMessage struct {
UserID64 int64 `json:"user_id"` MsgID64 int64 `json:"msg_id"`
Direction MsgDirection `json:"direction"` UserID64 int64 `json:"user_id"`
MsgText string `json:"msg"` Direction MsgDirection `json:"direction"`
MsgID64 int64 `json:"msg_id"` MsgText string `json:"msg"`
} }
const user_chtwrsbot = 408101137 const user_chtwrsbot = 408101137
var ownUserID64 = int64(0) var ownUserID64 = int64(0)
var ownUserID32 = int32(0) var ownUserID32 = int32(0)
func main() { func main() {
// msgMutex = &sync.Mutex{} // msgMutex = &sync.Mutex{}
tdlib.SetLogVerbosityLevel(1) tdlib.SetLogVerbosityLevel(1)
tdlib.SetFilePath("./errors.txt") tdlib.SetFilePath("./errors.txt")
// Create new instance of client // Create new instance of client
client := tdlib.NewClient(tdlib.Config{ client := tdlib.NewClient(tdlib.Config{
APIID: "187786", APIID: "187786",
APIHash: "e782045df67ba48e441ccb105da8fc85", APIHash: "e782045df67ba48e441ccb105da8fc85",
SystemLanguageCode: "en", SystemLanguageCode: "en",
DeviceModel: "ChatWarsClient", DeviceModel: "ChatWarsClient",
SystemVersion: "0.1", SystemVersion: "0.1",
ApplicationVersion: "0.1", ApplicationVersion: "0.1",
UseMessageDatabase: true, UseMessageDatabase: true,
UseFileDatabase: true, UseFileDatabase: true,
UseChatInfoDatabase: true, UseChatInfoDatabase: true,
UseTestDataCenter: false, UseTestDataCenter: false,
DatabaseDirectory: "./tdlib-db", DatabaseDirectory: "./tdlib-db",
FileDirectory: "./tdlib-files", FileDirectory: "./tdlib-files",
IgnoreFileNames: false, IgnoreFileNames: false,
}) })
for { for {
currentState, _ := client.Authorize() currentState, _ := client.Authorize()
if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPhoneNumberType { if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPhoneNumberType {
fmt.Print("Enter phone: ") fmt.Print("Enter phone: ")
var number string var number string
fmt.Scanln(&number) fmt.Scanln(&number)
_, err := client.SendPhoneNumber(number) _, err := client.SendPhoneNumber(number)
if err != nil { if err != nil {
fmt.Printf("Error sending phone number: %v", err) fmt.Printf("Error sending phone number: %v", err)
} }
} else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitCodeType { } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitCodeType {
fmt.Print("Enter code: ") fmt.Print("Enter code: ")
var code string var code string
fmt.Scanln(&code) fmt.Scanln(&code)
_, err := client.SendAuthCode(code) _, err := client.SendAuthCode(code)
if err != nil { if err != nil {
fmt.Printf("Error sending auth code : %v", err) fmt.Printf("Error sending auth code : %v", err)
} }
} else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPasswordType { } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateWaitPasswordType {
fmt.Print("Enter Password: ") fmt.Print("Enter Password: ")
var password string var password string
fmt.Scanln(&password) fmt.Scanln(&password)
_, err := client.SendAuthPassword(password) _, err := client.SendAuthPassword(password)
if err != nil { if err != nil {
fmt.Printf("Error sending auth password: %v", err) fmt.Printf("Error sending auth password: %v", err)
} }
} else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateReadyType { } else if currentState.GetAuthorizationStateEnum() == tdlib.AuthorizationStateReadyType {
fmt.Println("Authorization Ready! Let's rock") fmt.Println("Authorization Ready! Let's rock")
break break
} }
} }
ownUserID32 = OwnUserID(client) ownUserID32 = OwnUserID(client)
ownUserID64 = int64(OwnUserID(client)) ownUserID64 = int64(OwnUserID(client))
go ListenCW(client) go ListenCW(client)
fmt.Println("Started !") fmt.Println("Started !")
// Main loop // Main loop
for { for {
time.Sleep(30 * time.Second) time.Sleep(30 * time.Second)
} }
} }
func ListenCW(c *tdlib.Client) { func ListenCW(c *tdlib.Client) {
eventFilter := func(msg *tdlib.TdMessage) bool { eventFilter := func(msg *tdlib.TdMessage) bool {
updateMsg := (*msg).(*tdlib.UpdateNewMessage) updateMsg := (*msg).(*tdlib.UpdateNewMessage)
chatID := updateMsg.Message.ChatID chatID := updateMsg.Message.ChatID
if (chatID == user_chtwrsbot) { if chatID == user_chtwrsbot {
return true return true
} }
return false return false
} }
conn, err := amqp.Dial("amqp://shoopea:UmDd5g4WRa2MzqOHsG2T@localhost:5672/chatwars_shoopea") conn, err := amqp.Dial("amqp://shoopea:UmDd5g4WRa2MzqOHsG2T@localhost:5672/chatwars")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer conn.Close() defer conn.Close()
ch, err := conn.Channel() ch, err := conn.Channel()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
defer ch.Close() defer ch.Close()
q, err := ch.QueueDeclare( q, err := ch.QueueDeclare(
"msg", // name "msg", // name
false, // durable false, // durable
false, // delete when unused false, // delete when unused
false, // exclusive false, // exclusive
false, // no-wait false, // no-wait
nil, // arguments nil, // arguments
) )
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
receiver := c.AddEventReceiver(&tdlib.UpdateNewMessage{}, eventFilter, 100) receiver := c.AddEventReceiver(&tdlib.UpdateNewMessage{}, eventFilter, 100)
for newMsg := range receiver.Chan { for newMsg := range receiver.Chan {
updateMsg := (newMsg).(*tdlib.UpdateNewMessage) updateMsg := (newMsg).(*tdlib.UpdateNewMessage)
senderUserID := updateMsg.Message.SenderUserID senderUserID := updateMsg.Message.SenderUserID
mType := updateMsg.Message.Content.GetMessageContentEnum() mType := updateMsg.Message.Content.GetMessageContentEnum()
if mType == "messageText" { if mType == "messageText" {
user, err := c.GetUser(senderUserID) user, err := c.GetUser(senderUserID)
if err != nil { if err != nil {
fmt.Println("ListenCW:", err.Error()) fmt.Println("ListenCW:", err.Error())
continue continue
} }
txt := updateMsg.Message.Content.(*tdlib.MessageText).Text.Text txt := updateMsg.Message.Content.(*tdlib.MessageText).Text.Text
t := time.Now() t := time.Now()
m := ChatWarsMessage{ m := ChatWarsMessage{
UserID64 : ownUserID64, UserID64: ownUserID64,
MsgText : string(txt), MsgText: string(txt),
MsgID64 : updateMsg.Message.ID, MsgID64: updateMsg.Message.ID,
} }
if senderUserID == ownUserID32 { if senderUserID == ownUserID32 {
m.Direction = Outgoing m.Direction = Outgoing
} else { } else {
m.Direction = Incoming m.Direction = Incoming
} }
b, err := json.Marshal(m) b, err := json.Marshal(m)
_ = ch.Publish( _ = ch.Publish(
"", // exchange "", // exchange
q.Name, // routing key q.Name, // routing key
false, // mandatory false, // mandatory
false, // immediate false, // immediate
amqp.Publishing{ amqp.Publishing{
ContentType: "application/json", ContentType: "application/json",
Body: []byte(b), Body: []byte(b),
}) })
fmt.Printf("[%d-%02d-%02d %02d:%02d:%02d-00:00]", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
fmt.Println(" === CHATWARS (", user.Username, ") =====================================================================")
fmt.Println(txt, "\n")
fmt.Println("************ DETAILS ************")
fmt.Println("ID : ", updateMsg.Message.ID)
fmt.Println("SenderUserID : ", updateMsg.Message.SenderUserID)
fmt.Println("ChatID : ", updateMsg.Message.ChatID)
fmt.Println("SendingState : ", updateMsg.Message.SendingState)
fmt.Println("IsOutgoing : ", updateMsg.Message.IsOutgoing)
fmt.Println("CanBeEdited : ", updateMsg.Message.CanBeEdited)
fmt.Println("CanBeForwarded : ", updateMsg.Message.CanBeForwarded)
fmt.Println("IsChannelPost : ", updateMsg.Message.IsChannelPost)
fmt.Println("ContainsUnreadMention : ", updateMsg.Message.ContainsUnreadMention)
fmt.Println("ForwardInfo : ", updateMsg.Message.ForwardInfo)
fmt.Println("ReplyToMessageID : ", updateMsg.Message.ReplyToMessageID)
fmt.Println("ViaBotUserID : ", updateMsg.Message.ViaBotUserID)
fmt.Println("================================================================================================================")
}
fmt.Printf("[%d-%02d-%02d %02d:%02d:%02d-00:00]", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) }
fmt.Println(" === CHATWARS (", user.Username, ") =====================================================================")
fmt.Println(txt, "\n")
fmt.Println("************ DETAILS ************")
fmt.Println("ID : ", updateMsg.Message.ID)
fmt.Println("SenderUserID : ", updateMsg.Message.SenderUserID)
fmt.Println("ChatID : ", updateMsg.Message.ChatID)
fmt.Println("SendingState : ", updateMsg.Message.SendingState)
fmt.Println("IsOutgoing : ", updateMsg.Message.IsOutgoing)
fmt.Println("CanBeEdited : ", updateMsg.Message.CanBeEdited)
fmt.Println("CanBeForwarded : ", updateMsg.Message.CanBeForwarded)
fmt.Println("IsChannelPost : ", updateMsg.Message.IsChannelPost)
fmt.Println("ContainsUnreadMention : ", updateMsg.Message.ContainsUnreadMention)
fmt.Println("ForwardInfo : ", updateMsg.Message.ForwardInfo)
fmt.Println("ReplyToMessageID : ", updateMsg.Message.ReplyToMessageID)
fmt.Println("ViaBotUserID : ", updateMsg.Message.ViaBotUserID)
fmt.Println("================================================================================================================")
}
}
} }
func ForwardMsg(c *tdlib.Client, msgID int64, fromChatID int64, toChatID int64) (int64) { func ForwardMsg(c *tdlib.Client, msgID int64, fromChatID int64, toChatID int64) int64 {
msgIDs := make([]int64, 1) msgIDs := make([]int64, 1)
msgIDs[0] = msgID msgIDs[0] = msgID
msgs, _ := c.ForwardMessages(toChatID, fromChatID, msgIDs, false, false, false) msgs, _ := c.ForwardMessages(toChatID, fromChatID, msgIDs, false, false, false)
if msgs != nil { if msgs != nil {
return msgs.Messages[0].ID return msgs.Messages[0].ID
} else { } else {
return 0 return 0
} }
} }
@ -212,8 +209,7 @@ func DeleteMsg(c *tdlib.Client, chatID int64, msgID int64) {
fmt.Println("Deleting message ", msgID) fmt.Println("Deleting message ", msgID)
} }
func OwnUserID(c *tdlib.Client) (int32) { func OwnUserID(c *tdlib.Client) int32 {
user, _ := c.GetMe() user, _ := c.GetMe()
return user.ID; return user.ID
} }