Skip to content

Instantly share code, notes, and snippets.

@oliveira-andre
Created August 9, 2021 04:23
Show Gist options
  • Save oliveira-andre/e3de7a5fcfc8b0cf7a23993e06f8b040 to your computer and use it in GitHub Desktop.
Save oliveira-andre/e3de7a5fcfc8b0cf7a23993e06f8b040 to your computer and use it in GitHub Desktop.
in my search i didnt find a simple way to make one telegram bot with sinatra, then i make one very simple

create the route to configure webhook

get '/' do
  require 'telegram/bot'
  TOKEN = 'your token'
  HOOK_URL = 'https://example.com'
  bot = Telegram::Bot::Api.new(TOKEN)
  puts bot.set_webhook(url: HOOK_URL)

  content_type :json, charset: 'utf-8'
  { webhook: true }.to_json
end

Create a route to execute the telegram bot by webook

post '/' do
    request.body.rewind
    data = JSON.parse(request.body.read)
    @bot = Telegram::Bot::Api.new(TOKEN)
    @message = Telegram::Bot::Types::Update.new(data).message

    case @message.text
        when '/start'
            @bot.send_message(chat_id: @message.chat.id, text: "Hi, #{@message.from.first_name}, nice to see you")
        when '/stop'
            @bot.send_message(chat_id: @message.chat.id, text: "Bye, #{@message.from.first_name}")
        when '/help'
            @bot.send_message(chat_id: @message.chat.id, text: "some help...")
        else
            # do something with the message
            # maybe check for attachment
            if @message.photo.any? then
                result = @bot.getFile(file_id: @message.photo.last.file_id)
                telegramurl = "#{API}#{ENV['TELEGRAM_BOT_API_TOKEN']}/#{result["result"]["file_path"]}" if result["ok"]
                # download photo and process
            end
            @bot.send_message(chat_id: @message.chat.id, text: "Thank you, #{@message.from.first_name}")
    end    
    status 200
end
@gitDbits
Copy link

gitDbits commented Aug 9, 2021

Vlw man por compartilhar!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment