Skip to content

Instantly share code, notes, and snippets.

@donnfelker
Created October 15, 2024 10:45
Show Gist options
  • Save donnfelker/af58b2d34ef37e0b50abc5b6a5a80d04 to your computer and use it in GitHub Desktop.
Save donnfelker/af58b2d34ef37e0b50abc5b6a5a80d04 to your computer and use it in GitHub Desktop.
Ruby Telegram Bot Message Script
# TelegramMessenger Usage
# Replace 'YOUR_BOT_API_TOKEN' and 'CHAT_ID' with your actual bot token and chat ID
bot_token = 'your-bot-token'
chat_id = 'your-chat-id'
# Create an instance of the TelegramMessenger class
telegramer = TelegramMessenger.new(bot_token, chat_id)
# Create a multi-line string for the message
message = <<~MESSAGE
Check out *this* ruby method:
```ruby
def foo
puts "bar"
end
```
Now you can see the code in a code block.
This is a test message.
MESSAGE
# Find the chat_id by running (look in the output for the chat_id).
# You will need to have sent a message recently to the bot to get the chat_id.
telegramer.get_updates
# Once you have a chat_id, update the file with the chat_id and run the following to send a message:
#telegramer.send_message(message)
require 'telegram/bot' # RE: gem install telegram-bot-ruby
class TelegramMessenger
def initialize(bot_token, chat_id)
@bot_token = bot_token
@chat_id = chat_id
end
def get_updates
Telegram::Bot::Client.run(@bot_token) do |bot|
puts "Bot is running"
updates = bot.api.getUpdates
puts updates.to_json
puts "Bot is done running"
end
end
def escape_markdown(text)
# Replace each special character with the escaped version
text.gsub(/([\\\_\*\[\]\(\)\~\>\#\+\-\=\|\{\}\.\!])/) { |match| "\\#{match}" }
end
def send_message(message, parse_mode = 'MarkdownV2', chat_id = nil)
puts "Sending message ... #{message}"
chat_id ||= @chat_id
Telegram::Bot::Client.run(@bot_token) do |bot|
bot.api.send_message(chat_id: , text: escape_markdown(message), parse_mode: )
end
puts "Message sent!"
rescue => e
puts "Failed to send message: #{e.message}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment