我使用以下代码从Telegram chat中读取新消息:
public async Task GatherChatHistory(string channelName, string ch_id, string mid, int offset = 0, int minId = 0, int maxId = -1, int limit = 100)
{
Log.Info(Tag, "In GatherChatHistory Start");
TelegramClient client = CreateClient();
await InitializeAndAuthenticateClient(client);
int maximal = Convert.ToInt32(mid);
Log.Info(Tag, "In GatherChatHistory Before GetUserDialogAsync");
try
{
var dialogs = (TLDialogs)await client.GetUserDialogsAsync();
var chat = dialogs.chats.lists
.OfType<TLChat>()
.FirstOrDefault(c => c.title == channelName);
Log.Info(Tag, "In GatherChatHistory After GetUserDialogAsync " + (chat != null));
if (chat != null)
{
Log.Info(Tag, "Chat != null, " + channelName);
try
{
var tlAbsMessages =
await client.GetHistoryAsync(
new TLInputPeerChat { chat_id = chat.id }, offset,
minId, maxId, limit);
Log.Info(Tag, "After GetHistoryAsync");
var tlChannelMessages = (TLMessages)tlAbsMessages;
Log.Info(Tag, "GatherChatHistory Messages count = " + (tlChannelMessages.messages.lists.Count - 1));
for (var index = 0; index < tlChannelMessages.messages.lists.Count - 1; index++)
{
var tlAbsMessage = tlChannelMessages.messages.lists[index];
Log.Info(Tag, "Message Type = " + tlAbsMessage.GetType());
if (tlAbsMessage.GetType().ToString().Equals("TeleSharp.TL.TLMessageService"))
continue;
var message = (TLMessage)tlAbsMessage;
if (message.id == maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " maximal was reached");
break;
}
if (message.id <= maximal)
{
Log.Info(Tag, "GatherChatHistory Chat_id = " + channelName + " message.id = " + message.id + " maxid = " + maximal);
continue;
}
if (message.media == null)
{
Log.Info(Tag, "Message ID = " + message.id);
Log.Info(Tag, "Chat ID = " + chat.id);
Log.Info(Tag, "Content = " + message.message);
await AddNewMessageToDatabase(channelName, ch_id, message.message, null, message.from_id.GetValueOrDefault(), message.id);
}
else
{
switch (message.media.GetType().ToString())
{
case "TeleSharp.TL.TLMessageMediaPhoto":
var tLMessageMediaPhoto = (TLMessageMediaPhoto)message.media;
var photo = (TLPhoto)tLMessageMediaPhoto.photo;
var photoSize = photo.sizes.lists.OfType<TLPhotoSize>().Last();
TLFileLocation tf = (TLFileLocation)photoSize.location;
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
using (var ms = new MemoryStream(resFile.bytes))
{
byte[] byteArr = ms.ToArray();
string base64image = Convert.ToBase64String(byteArr);
Log.Info(Tag, "Caption = " + tLMessageMediaPhoto.caption);
Log.Info(Tag, "Base64 Image = " + base64image);
await AddNewMessageToDatabase(channelName, ch_id, tLMessageMediaPhoto.caption, base64image, message.from_id.GetValueOrDefault(), message.id);
}
break;
case "TeleSharp.TL.TLMessageMediaDocument":
var tLMessageMediaDocument = (TLMessageMediaDocument)message.media;
break;
case "TeleSharp.TL.TLMessageMediaWebPage":
var tLMessageMediaWebPage = (TLMessageMediaWebPage)message.media;
string url = string.Empty;
if (tLMessageMediaWebPage.webpage.GetType().ToString() != "TeleSharp.TL.TLWebPageEmpty")
{
var webPage = (TLWebPage)tLMessageMediaWebPage.webpage;
url = webPage.url;
}
break;
}
}
}
}
catch (Exception e)
{
Logger.Error("Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History exception: " + e.Message);
Log.Error(Tag, "Telegram Chat History StackTrace = " + e.ToString());
}
}
else
Log.Info(Tag, "Chat == null");
}
catch (Exception e)
{
Log.Error(Tag, "ReadUserAsync Error : " + e.Message);
}
}
我每分钟检查聊天新消息一次。我对短信没有任何问题,所有这些都没有任何问题。我也可以看一张照片,但每次只能看一张。如果在聊天中,在阅读照片后有多张照片或照片和短信,TLSharp会抛出异常:
[MessagingService:TelegramBridge] Telegram Chat History exception: msg_seqno
too low (the server has already received a message with a lower msg_id but
with either a higher or an equal and odd seqno)
[MessagingService:TelegramBridge] Telegram Chat History StackTrace =
System.InvalidOperationException: msg_seqno too low (the server has already
received a message with a lower msg_id but with either a higher or an equal
and odd seqno)
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.HandleBadMsgNotification (System.UInt64
messageId, System.Int32 sequence, System.IO.BinaryReader messageReader)
[0x0009f] in <24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at
TLSharp.Core.Network.MtProtoSender.processMessage (System.UInt64 messageId,
System.Int32 sequence, System.IO.BinaryReader messageReader,
TeleSharp.TL.TLMethod request) [0x00182] in
<24dee86ac15149c89ccf3cac229b439d>:0
[MessagingService:TelegramBridge] at TLSharp.Core.Network.MtProtoSender+
<Receive>d__9.MoveNext () [0x000bb] in <24dee86ac15149c89ccf3cac229b439d>:0
有人可以帮我解决这个问题吗?
UPD 我将错误的位置本地化:
var resFile = await client.GetFile(new TLInputFileLocation
{
local_id = tf.local_id,
secret = tf.secret,
volume_id = tf.volume_id
}, 0);
但我还是不知道该做什么...... 的 UPD 这是主要功能:
async Task<int> WriteMessagesFromChannels()
{
Log.Info(Tag, "In WriteMessagesFromChannels");
var url = "http://" + MainActivity.Host + ":" + MainActivity.Port + MainActivity.Url + "/groups?page=1&pageSize=10000";
Log.Info(Tag, "URL = " + url);
var json = FetchServerData(url);
if (json == null)
{
Log.Info(Tag, "In WriteMessagesFromChannels: JSON = NULL");
return -1;
}
var obj = JObject.Parse(json);
var groups = JsonConvert.DeserializeObject<TelegramChannel[]>(obj["data"]["items"].ToString());
Log.Info(Tag, "In WriteMessagesFromChannels: size = " + groups.Length);
if (groups != null)
{
foreach (var gr in groups)
{
Log.Info(Tag, "Group name = " + gr.name + ", monitor = " + gr.monitor);
if (gr.ischannel == true || gr.monitor == false)
continue;
string maxid = ReadMaxId(gr.id);
if (maxid == "")
continue;
Log.Info(Tag, "In WriteMessagesFromChannels: MAXID = " + maxid);
await ReadMessagesFromChat(gr.name, gr.id, maxid);
Thread.Sleep(3000);
}
Log.Info(Tag, "In WriteMesasagesFromChannels: CYCLE IS FINISHED");
}
else
{
Log.Info(Tag, "In WriteMessagesFromChannels: GROUPS = NULL");
}
return 1;
}
async Task<int> ReadMessagesFromChat(string name, string ch_id, string maxid)
{
Log.Info(Tag, "In ReadMessagesFromChat");
//await bridge.GetPhotoFromChannel(name);
await bridge.GatherChatHistory(name, ch_id, maxid);
return 1;
}