首页 > 解决方案 > VB.Net 将项目添加到 Telegram.bot 的回复键盘

问题描述

我正在使用 VB.Net (VS2019) 和Telegram.bot API。在 C# 示例中,它们展示了如何将项目添加到回复键盘。恐怕我根本不理解这个IEnumerable概念,但无论如何我已经设法将 C# 转换为工作 VB.Net 代码。

这是代码:C#

 if (update.Message.Text.Contains("/reply"))
    {
      var keyboard = new ReplyKeyboardMarkup
      {
       Keyboard = new KeyboardButton[][]{
                  new KeyboardButton[]{
                  new KeyboardButton("Button 1"), //column 1 row 1
                  new KeyboardButton("Button 2") //column 1 row 2
                },// column 1
                  new KeyboardButton[]{
                  new KeyboardButton("Button 3") //col 2 row 1
                } // column 2
       },
       ResizeKeyboard = true
    }; ;
   bot.SendMessage(update.Message.Chat.Id, "new keyboard", replyMarkup: keyboard);
}

VB代码是

If update.Message.Text.Contains("/reply") Then
    Dim keyboard = New ReplyKeyboardMarkup With {
        .Keyboard = New KeyboardButton()() {New KeyboardButton() {New KeyboardButton("Button 1"), New KeyboardButton("Button 2")}, New KeyboardButton() {New KeyboardButton("Button 3")}},
        .ResizeKeyboard = True
    }
    bot.SendMessage(update.Message.Chat.Id, "new keyboard", replyMarkup:=keyboard)
End If

我的问题是如何即时更新它?我从 sqlite 读取表格,我想创建按钮来保存记录的 rowids.. 所以我有

 mySQL = "select * from products;"
 Dim cs As String = "URI=file:" & DBName
Using con As New SQLiteConnection(cs)
   con.Open()
   Dim dr As SQLiteDataReader
   Using DBcmd As New SQLiteCommand(con)
       DBcmd.CommandText = mySQL
       dr = DBcmd.ExecuteReader()
       While dr.Read()
           MsgText &= String.Format("Code: *{0}* [{1}]({3}), Price: ${2}", dr("Code"), Replace(dr("ProdName"), "-", " "), dr("Price"), dr("ProdURL")) & vbCrLf
       End While
    End Using
    con.Close()
End Using

在那个循环中,我想构建键盘,为每个出现的 按钮添加一个按钮 dr("code")作为按钮的文本。

请帮忙?

标签: c#vb.nettelegram-botienumerable

解决方案


一种选择是创建一个List(Of KeyboardButton()),即一个泛型ListKeyboardButton数组。您可以循环读取数据阅读器,KeyboardButton为当前记录创建一个数组并将其添加到List. 最后,调用ToArrayList获得KeyboardButton可以分配给Keyboard属性的锯齿状数组。例如

Dim keyboardButtons As New List(Of KeyboardButton())

While dr.Read()
    keyboard.Add({New KeyboardButton(dr.GetString(dr.GetOrdinal("Code")))})
End While

Dim keyboard As New ReplyKeyboardMarkup With {.Keyboard = keyboardButtons.ToArray()}

推荐阅读