如何从电报机器人创建私人消息?

时间:2018-08-08 11:30:30

标签: c# .net telegram telegram-bot telegram-webhook

我正在通过Webhook连接到电报机器人,我想通过电报在私人聊天中进行响应,但是如果我发送UID,它不会从该机器人向用户发送任何消息。

这就是我所做的。

  1. 我使用.net框架创建了一个Web API项目,以通过电报bot连接到webhook。
  2. 作为用户,我编写了一个命令,该命令将返回一些对象列表。
  3. 从WebAPI中我得到了命令并已正确处理
  4. 在发送回响应时,我通过了此{“ method”:“ sendMessage”,“ chat_id”:“ [发送命令的用户的UID]”,“ text”:“ [返回列表转换为字符串]”,“ reply_to_message_id “:” [命令的消息ID]“}

这是我要发送的实际代码

return new TelegramResponseModel 
{ method = "sendMessage", chat_id = newUpdate.message.chat.id.ToString(),
  text = text, reply_to_message_id = newUpdate.message.message_id };
  1. 在电报上什么也没发生!

2 个答案:

答案 0 :(得分:0)

您可以使用Nuget软件包库来实现与称为Telegram.Bot的Telegram的集成。此外,还有few examples如何使用此库。 例如,此简短程序演示了如何使用WebHook的

using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.Owin.Hosting;
using Owin;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using File = System.IO.File;

namespace Telegram.Bot.Examples.WebHook
{
    public static class Bot
    {
        public static readonly TelegramBotClient Api = new TelegramBotClient("Your API Key");
    }

    public static class Program
    {
        public static void Main(string[] args)
        {
            // Endpoint must be configured with netsh:
            // netsh http add urlacl url=https://+:8443/ user=<username>
            // netsh http add sslcert ipport=0.0.0.0:8443 certhash=<cert thumbprint> appid=<random guid>

            using (WebApp.Start<Startup>("https://+:8443"))
            {
                // Register WebHook
                // You should replace {YourHostname} with your Internet accessible hosname
                Bot.Api.SetWebhookAsync("https://{YourHostname}:8443/WebHook").Wait();

                Console.WriteLine("Server Started");

                // Stop Server after <Enter>
                Console.ReadLine();

                // Unregister WebHook
                Bot.Api.DeleteWebhookAsync().Wait();
            }
        }
    }

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute("WebHook", "{controller}");

            app.UseWebApi(configuration);
        }
    }

    public class WebHookController : ApiController
    {
        public async Task<IHttpActionResult> Post(Update update)
        {
            var message = update.Message;

            Console.WriteLine("Received Message from {0}", message.Chat.Id);

            if (message.Type == MessageType.Text)
            {
                // Echo each Message
                await Bot.Api.SendTextMessageAsync(message.Chat.Id, message.Text);
            }
            else if (message.Type == MessageType.Photo)
            {
                // Download Photo
                var file = await Bot.Api.GetFileAsync(message.Photo.LastOrDefault()?.FileId);

                var filename = file.FileId + "." + file.FilePath.Split('.').Last();

                using (var saveImageStream = File.Open(filename, FileMode.Create))
                {
                    await Bot.Api.DownloadFileAsync(file.FilePath, saveImageStream);
                }

                await Bot.Api.SendTextMessageAsync(message.Chat.Id, "Thx for the Pics");
            }

            return Ok();
        }
    }
}

答案 1 :(得分:0)

这里有一个关于 php 的功能代码:

<?php


$token = 'yout_boot_tocken';
$website = 'https://api.telegram.org/bot'.$token;

$input = file_get_contents('php://input');
$update = json_decode($input, TRUE);

$chatId = $update['message']['chat']['id'];
$message = $update['message']['text'];

$messageCode = strtoupper($message);

switch($messageCode) {
    case 'hello':
        $response = 'Hello my friend... how are you?';
        sendMessage($chatId, $response);
        break;
    case 'address':
        $response = 'Your Addres is Rosent wallet 245';
        sendMessage($chatId, $response);
        break;
    case '/INFO':
        $response = 'Hi, i am a Boot';
        sendMessage($chatId, $response);
        break;
    case 'bye':
        $response = 'it was a pleasure chat with you';
        sendMessage($chatId, $response);
        break;
    default:
        $response = 'I dont understand what do you mean with '.$messageCode;
        sendMessage($chatId, $response);
        break;
}

function sendMessage($chatId, $response) {
    $url = $GLOBALS['website'].'/sendMessage? 
 chat_id='.$chatId.'&parse_mode=HTML&text='.urlencode($response);
    file_get_contents($url);
}
  ?>