几天来,我一直在尝试用Telegram Bot解决此问题。
在他“ /启动”机器人之后,我正在尝试向用户发送一些问题。
我想捕获所有用户答案,然后将其发送给某个我想在一条消息中查看用户答案的用户。
我试图通过发送内联按钮来做到这一点,但是找不到等待用户下一条消息的方法。我试图将答案存储在字符串数组中,但也不起作用。
在问题的结尾,我想在一条消息中将所有用户问题的所有用户答案发送给某个用户ID /频道。
我使用Telegram.Bot库。
这是我的代码
static string gotName = "0";
static string gotAge = "0";
static string gotMessage = "0";
static string[] Forminfo = { gotName, gotAge, gotMessage };
async private void Bot_OnUpdate(object sender, Telegram.Bot.Args.UpdateEventArgs e)
{
if (e.Update.Type == UpdateType.Message && e.Update.Message.Text == "/start")
{
var streg = new InlineKeyboardMarkup(new[]
{
new [] // first row
{
InlineKeyboardButton.WithCallbackData("Next Step","start")
}
});
var update = e.Update.Message.Text;
var strmsg = "To Start The Register please send the bot your name and click on Next Step";
await bot.SendTextMessageAsync(e.Update.Message.Chat.Id, strmsg, ParseMode.Html, replyMarkup: streg);
var usermsg = await bot.GetUpdatesAsync();
Forminfo[0] = usermsg.ToString();
}
}
async private void Bot_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
{
var streg1 = new InlineKeyboardMarkup(new[]
{
new [] // first row
{
InlineKeyboardButton.WithCallbackData("Next","start1")
}
});
if (Forminfo[0] != "0")
{
var startedmsg = "Hello " + Forminfo[0].ToString() + "\n" +
"Please Send us your Age and click Next";
try
{
await bot.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, startedmsg, ParseMode.Html, replyMarkup: streg1);
}
catch(HttpRequestException ex)
{
await bot.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, "To Many Request Please Try Later.", ParseMode.Html);
}
}
}
答案 0 :(得分:1)
有几处要解决的问题:
OnUpdate
回调中处理的只是消息,请改用OnMessage
OnUpdate
,然后手动调用GetUpdates
。您无法混合使用多种获取更新的方法-StartReceiving
调用已经可以处理内部的GetUpdates
调用。Dictionary<userId, result>
。SendTextMessageAsync
通话中,如果要发送常规文本,则无需设置ParseMode
这是一个代码示例,可以执行您想要的操作,但完全不验证输入:
const long TargetChannelId = 123456;
static readonly ConcurrentDictionary<int, string[]> Answers = new ConcurrentDictionary<int, string[]>();
private static async void Bot_OnMessage(object sender, MessageEventArgs e)
{
Message message = e.Message;
int userId = message.From.Id;
if (message.Type == MessageType.Text)
{
if (Answers.TryGetValue(userId, out string[] answers))
{
if (answers[0] == null)
{
answers[0] = message.Text;
await Bot.SendTextMessageAsync(message.Chat, "Now send me your age");
}
else if (answers[1] == null)
{
answers[1] = message.Text;
await Bot.SendTextMessageAsync(message.Chat, "Now send me your message");
}
else
{
Answers.TryRemove(userId, out string[] _);
await Bot.SendTextMessageAsync(message.Chat, "Thank you, that's all I need from you");
string answersText = $"User {answers[0]}, aged {answers[1]} sent the following message:\n{message.Text}";
await Bot.SendTextMessageAsync(TargetChannelId, answersText);
}
}
else
{
Answers.TryAdd(userId, new string[2]);
await Bot.SendTextMessageAsync(message.Chat, "Please send me your name");
}
}
}