Golang中如何避免获取channel的更新

Golang中如何避免获取channel的更新 大家好,

我正在使用 TDlib 开发一个 Telegram Golang 程序。 每次运行程序时,它都会获取大约一小时或更早之前的约 20 条消息。 我希望避免获取这些消息,非常感谢您的建议。

通常,我会收到实例未激活时错过的所有消息。如果错过了很多消息,启动后很快就会收到大量 updateNewMessage 更新。

我希望通过检查消息的发送 date,跳过所有在实例启动前发送的消息更新。

我的程序大致如下:

// 每 5 秒向 Foursquare 机器人聊天发送 "/start" 文本
go func() {
    // 应该以某种方式获取 chatID,请查看 "getChats" 示例
    chatID := int64(198529620) // Foursquare 机器人聊天 ID

    inputMsgTxt := tdlib.NewInputMessageText(tdlib.NewFormattedText("/start", nil), true, true)
    client.SendMessage(chatID, 0, 0, nil, nil, inputMsgTxt)

    time.Sleep(5 * time.Second)
}()

// rawUpdates 获取来自 tdlib 的所有更新
rawUpdates := client.GetRawUpdatesChannel(100)
for update := range rawUpdates {
    // 显示所有更新
    fmt.Println(update.Data)
    fmt.Print("\n\n")
}

非常感谢您的建议。

祝好


更多关于Golang中如何避免获取channel的更新的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang中如何避免获取channel的更新的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


要避免获取历史消息更新,可以通过在启动时设置tdlib.Client的适当参数,并在处理更新时过滤掉旧消息。以下是具体实现方案:

1. 配置TDlib客户端忽略历史消息

在创建客户端时,设置tdlib.TdlibParameters来避免获取历史更新:

import (
    "github.com/zelenin/go-tdlib/client"
    "time"
)

func createClient() (*client.Client, error) {
    tdlibParams := &client.TdlibParameters{
        ApiId:               YOUR_API_ID,
        ApiHash:             YOUR_API_HASH,
        SystemLanguageCode:  "en",
        DeviceModel:         "Server",
        ApplicationVersion:  "1.0.0",
        UseMessageDatabase:  true,
        UseSecretChats:      false,
        SystemVersion:       "1.0",
        DatabaseDirectory:   "./tdlib-db",
        FilesDirectory:      "./tdlib-files",
    }
    
    // 创建客户端配置
    config := client.Config{
        TdlibParameters: tdlibParams,
    }
    
    // 设置客户端忽略历史消息
    config.IgnoreFileNames = []string{"tdlib.log"}
    
    return client.NewClient(config)
}

2. 在更新处理中过滤旧消息

修改你的更新处理逻辑,基于消息日期进行过滤:

package main

import (
    "fmt"
    "time"
    "github.com/zelenin/go-tdlib/client"
)

func main() {
    // 记录程序启动时间
    programStartTime := time.Now().Unix()
    
    // 创建客户端
    c, err := createClient()
    if err != nil {
        panic(err)
    }
    
    // 发送消息的goroutine
    go func() {
        chatID := int64(198529620)
        inputMsgTxt := client.NewInputMessageText(client.NewFormattedText("/start", nil), true, true)
        
        for {
            c.SendMessage(chatID, 0, 0, nil, nil, inputMsgTxt)
            time.Sleep(5 * time.Second)
        }
    }()
    
    // 获取更新通道
    rawUpdates := c.GetRawUpdatesChannel(100)
    
    for update := range rawUpdates {
        // 检查是否为消息更新
        if updateNewMessage, ok := update.Data.(*client.UpdateNewMessage); ok {
            // 获取消息日期
            messageDate := updateNewMessage.Message.Date
            
            // 只处理程序启动后发送的消息
            if messageDate >= programStartTime {
                fmt.Printf("新消息 [%s]: %v\n", 
                    time.Unix(messageDate, 0).Format("2006-01-02 15:04:05"),
                    updateNewMessage.Message.Content)
            } else {
                fmt.Printf("跳过历史消息 [%s]\n", 
                    time.Unix(messageDate, 0).Format("2006-01-02 15:04:05"))
                continue
            }
        }
        
        // 处理其他类型的更新
        fmt.Println(update.Data)
    }
}

3. 使用更精确的消息过滤

如果需要更精确的控制,可以检查消息的具体时间戳:

func shouldProcessMessage(msg *client.Message, startTime int64) bool {
    // 获取消息发送时间
    messageTime := msg.Date
    
    // 添加缓冲时间(例如5秒),避免边界情况
    bufferSeconds := int64(5)
    
    // 只处理启动时间之后的消息
    return messageTime > (startTime - bufferSeconds)
}

// 在更新循环中使用
for update := range rawUpdates {
    if updateNewMessage, ok := update.Data.(*client.UpdateNewMessage); ok {
        if !shouldProcessMessage(updateNewMessage.Message, programStartTime) {
            continue // 跳过历史消息
        }
        
        // 处理新消息
        processNewMessage(updateNewMessage.Message)
    }
}

4. 使用TDlib的offset参数(如果API支持)

某些TDlib方法允许指定offset来获取特定时间之后的消息:

// 获取聊天历史时指定offset
func getRecentMessages(c *client.Client, chatID int64, fromMessageID int64) {
    // 从特定消息ID开始获取
    messages, err := c.GetChatHistory(chatID, fromMessageID, 0, 100, false)
    if err != nil {
        fmt.Printf("获取消息历史失败: %v\n", err)
        return
    }
    
    for _, msg := range messages.Messages {
        fmt.Printf("消息ID: %d, 时间: %s\n", 
            msg.Id, 
            time.Unix(msg.Date, 0).Format("2006-01-02 15:04:05"))
    }
}

这种方法通过在程序启动时记录时间戳,并在处理每个updateNewMessage时检查消息的发送时间,确保只处理程序启动后接收到的消息更新。

回到顶部