我想在telegram.bot
例如:
我们有一个从数据库或其他recurses获取的字符串数组
我们如何将数据从数组推送到for循环或函数中的InlineKeyboardMarkup
//array of Button
string[] ButtonItem= new string[] { "one", "two", "three", "Four" };
//function or solution to create keyboard like this
var keyboard = new InlineKeyboardMarkup(new[]
{
new[]
{
new InlineKeyboardButton("one"),
new InlineKeyboardButton("two"),
},
new[]
{
new InlineKeyboardButton("three"),
new InlineKeyboardButton("Four"),
}
});
答案 0 :(得分:8)
您可以使用单独的函数来获取InlineKeyboardButton数组
private static InlineKeyboardButton[][] GetInlineKeyboard(string [] stringArray)
{
var keyboardInline = new InlineKeyboardButton[1][];
var keyboardButtons = new InlineKeyboardButton[stringArray.Length];
for (var i = 0; i < stringArray.Length; i++)
{
keyboardButtons[i] = new InlineKeyboardButton
{
Text = stringArray[i],
CallbackData = "Some Callback Data",
};
}
keyboardInline[0] = keyboardButtons;
return keyboardInline;
}
然后调用函数:
var buttonItem = new[] { "one", "two", "three", "Four" };
var keyboardMarkup = new InlineKeyboardMarkup(GetInlineKeyboard(buttonItem));
答案 1 :(得分:5)
在方法中创建InlineKeyboardMarkup:
public static InlineKeyboardMarkup InlineKeyboardMarkupMaker(Dictionary<int, string> items)
{
InlineKeyboardButton[][] ik = items.Select(item => new[]
{
new InlineKeyboardButton(item.Key, item.Value)
}).ToArray();
return new InlineKeyboardMarkup(ik);
}
然后像这样使用它:
var items=new Dictionary<int,string>()
{
{0 , "True" }
{1 , "False" }
};
var inlineKeyboardMarkup = InlineKeyboardMarkupMaker(items);
Bot.SendTextMessageAsync(message.Chat.Id, messageText, replyMarkup: inlineKeyboardMarkup);
选择True或False会使Update.CallbackQuery.Data
等于所选项目键(0或1)进行更新。
答案 2 :(得分:2)
通过以下方法创建具有特定列的InlineKeyboardButton。
public static IReplyMarkup CreateInlineKeyboardButton(Dictionary<string, string> buttonList, int columns)
{
int rows = (int)Math.Ceiling((double)buttonList.Count / (double)columns);
InlineKeyboardButton[][] buttons = new InlineKeyboardButton[rows][];
for (int i = 0; i < buttons.Length; i++)
{
buttons[i] = buttonList
.Skip(i * columns)
.Take(columns)
.Select(direction => new InlineKeyboardCallbackButton(
direction.Key, direction.Value
) as InlineKeyboardCallbackButton)
.ToArray();
}
return new InlineKeyboardMarkup(buttons);
}
使用这样的方法:
public static IReplyMarkup CreateInLineMainMenuMarkup()
{
Dictionary<string, string> buttonsList = new Dictionary<string, string>();
buttonsList.Add("one", "DATA1");
buttonsList.Add("two", "DATA2");
buttonsList.Add("three", "DATA3");
return CreateInlineKeyboardButton(buttonsList, 2);
}
感谢pouladpld创建此功能。