简体   繁体   中英

How can i create a private message from telegram bot?

I'm connecting to telegram bot with webhook and i wanted to respond in private chat through telegram but if i send UID it doesn't send any message to the user from the bot.

this is what i did.

  1. I created a Web API Project with .net framework to connect to webhook with telegram bot.
  2. As a user, i wrote a command that will return some list of objects.
  3. From the WebAPI i got the command and processed correctly
  4. on sending response back i passed this {"method":"sendMessage","chat_id":"[user's UID who sent the command]", "text":"[returning list converted as string]", "reply_to_message_id":"[message id for the command]"}

This is the actual code that i'm sending

return new TelegramResponseModel 
{ method = "sendMessage", chat_id = newUpdate.message.chat.id.ToString(),
  text = text, reply_to_message_id = newUpdate.message.message_id };
  1. on telegram nothing happens!!

You can use Nuget package library for implementing integration with Telegram called Telegram.Bot . Also there is few examples how you can use this library. For example this short program shows how you can use WebHook's

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();
        }
    }
}

here you have a functional code on 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);
}
  ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM