Class: Telepost

Inherits:
Object
  • Object
show all
Defined in:
lib/telepost.rb

Overview

Telepost is a simple gateway to Telegram, which can post messages and respond to primitive requests:

require 'telepost'
tp = Telepost.new('... secret token ...')
tp.run do |chat, msg|
  # Reply to the message via tp.post(msg, chat)
end

For more information read README file.

Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2018 Yegor Bugayenko

License

MIT

Defined Under Namespace

Classes: Fake

Instance Method Summary collapse

Constructor Details

#initialize(token, chats: []) ⇒ Telepost



63
64
65
66
67
# File 'lib/telepost.rb', line 63

def initialize(token, chats: [])
  @token = token
  @client = Telebot::Client.new(token)
  @chats = chats
end

Instance Method Details

#post(chat, *lines) ⇒ Object



90
91
92
93
94
95
96
97
98
99
# File 'lib/telepost.rb', line 90

def post(chat, *lines)
  @client.send_message(
    chat_id: chat,
    parse_mode: 'Markdown',
    disable_web_page_preview: true,
    text: lines.join(' ')
  )
rescue Telebot::Error => e
  raise "#{e.message}: \"#{msg}\""
end

#runObject

You can run a chat bot to listen to the messages coming to it, in a separate thread.



71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/telepost.rb', line 71

def run
  Telebot::Bot.new(@token).run do |chat, message|
    if block_given?
      yield(chat, message)
    elsif !chat.nil?
      post(
        "This is your chat ID: `#{message.chat.id}`.",
        chat: message.chat.id
      )
    end
  end
end

#spam(*lines) ⇒ Object



84
85
86
87
88
# File 'lib/telepost.rb', line 84

def spam(*lines)
  @chats.each do |chat|
    post(chat, lines)
  end
end