Skip to content

Instantly share code, notes, and snippets.

@AlexKMDev
Last active August 29, 2015 14:23
Show Gist options
  • Save AlexKMDev/d2bf558da3826e99239b to your computer and use it in GitHub Desktop.
Save AlexKMDev/d2bf558da3826e99239b to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'em-http-request'
require 'json'
def send_m(m, recipient)
token = ''
base = 'https://api.telegram.org/bot'
uri = "#{base}#{token}/sendMessage"
EM.run do
req = EM::HttpRequest.new(uri).get query: {chat_id:recipient, text:m.reverse}
req.callback do
print "#{req.response_header.status}: send new message\n"
end
req.errback do
print "#{req.response_header.status}: #{req.error}\n"
end
end
end
def update(offset)
token = ''
base = 'https://api.telegram.org/bot'
uri = "#{base}#{token}/getUpdates"
EM.run do
req = EM::HttpRequest.new(uri).get query: {offset: offset}
req.callback do
hash = JSON.parse(req.response)
result = hash['result']
print "#{req.response_header.status} - #{result.count} messages\n" if result.count > 0
result.each do |x|
m = x['message']
print "#{m['from']['username']}: #{m['text']}\n"
send_m(m['text'], m['from']['id']) unless m['text'].nil?
end
if result.count > 0
update(result.last['update_id'] + 1)
else
update(offset)
end
end
req.errback do
print "#{req.response_header.status}: #{req.error}\n"
update(offset)
end
end
end
update(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment