Giter Club home page Giter Club logo

rocketchatbot's Introduction

REST API based bot for Rocket.Chat

Install

pip install RocketChatAPIBot

Usage

Create new bot

import os
from RocketChatBot import RocketChatBot

botname = os.environ['BOTNAME']
botpassword = os.environ['BOTPASSWORD']
server_url = os.environ['BOT_URL']

bot = RocketChatBot(botname, botpassword, server_url)

Send message to channel

bot.send_message('starting bot...', channel_id='GENERAL')

Direct message handler

Gets triggered when sentence starts with the botname like '@botname echo hello'

def greet(msg, user, channel_id):
    bot.send_message('hello @' + user, channel_id)
    
bot.add_dm_handler(['hey', 'hello', ], greet)

Receives a list of keywords to trigger the command and the method to execute. The method should receive as parameters always msg as the message, user and channel_id

Auto answer handler

Gets triggered with the mention of keywords. Only made to respond with simple text, no functions.

bot.add_auto_answer(['good news', 'i have good news', ], ['hell yeah!', 'tell me, tell me!', 'you are already good news ;)', ])

Direct answer handler

Gets triggered when sentence starts with the name of the bot and keywords are in the sentence like '@botname who are you?'

bot.add_direct_answer(['who are you?', 'what is your name?', ], ['I am botname', ])

Handle unknow commands

bot.unknow_command = ['I do not know what you want me to do...', 'I\'m almost sure I\'m not programmed to do that', 'I have no idea how to do that so here is a hug :hugging:']

rocketchatbot's People

Contributors

jadolg avatar kaiwasaki avatar skyleronken avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

rocketchatbot's Issues

Connection Time out Errors

Traceback (most recent call last):
File "partsbot.py", line 124, in
bot.run()
File "/home/wesley/.local/lib/python3.8/site-packages/RocketChatBot.py", line 148, in run
for channel in self.api.channels_list_joined().json().get('channels'):
File "/home/wesley/.local/lib/python3.8/site-packages/rocketchat_API/rocketchat.py", line 293, in channels_list_joined
return self.__call_api_get('channels.list.joined', kwargs=kwargs)
File "/home/wesley/.local/lib/python3.8/site-packages/rocketchat_API/rocketchat.py", line 50, in __call_api_get
return self.req.get(
File "/usr/lib/python3/dist-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 529, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='mydomain.com', port=443): Read timed out. (read timeout=30)

Traceback (most recent call last):
File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
self.run()
File "/usr/lib/python3.8/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "/home/wesley/.local/lib/python3.8/site-packages/RocketChatBot.py", line 120, in process_channel
self.process_messages(self.api.channels_history(channel_id, oldest=self.lastts[channel_id]).json(),
File "/home/wesley/.local/lib/python3.8/site-packages/rocketchat_API/rocketchat.py", line 306, in channels_history
return self.__call_api_get('channels.history', roomId=room_id, kwargs=kwargs)
File "/home/wesley/.local/lib/python3.8/site-packages/rocketchat_API/rocketchat.py", line 50, in __call_api_get
return self.req.get(
File "/usr/lib/python3/dist-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 504, in send
raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='mydomain.com', port=443): Max retries exceeded with url: /api/v1/channels.history?roomId=LcxSQKEqEKNZJB3u5&oldest=2020-07-15T17:01:31.149Z (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x7fa4782d74f0>, 'Connection to mydomain.com timed out. (connect timeout=30)'))

Seems to happen randomly.

receive direct message

If a Rocket Chat user initiate a direct message to the robot, is there a way for the robot to receive the message in the direct conversation and send reply back?

Thanks,
Austin

Direct message handler not working

I am trying to implement add_dm_handler. However its not working. Here's my code sample

import os
from RocketChatBot import RocketChatBot
botname = os.environ['BOTNAME']
botpassword = os.environ['BOTPASSWORD']
server_url = os.environ['BOT_URL']
bot = RocketChatBot(botname, botpassword, server_url)

def greet(msg, user, channel_id):
bot.send_message('hello @' + user, channel_id)

try:
while True:
bot.add_dm_handler(['hey', 'hello', ], greet)
bot.add_auto_answer(['test'],['testbot'])
except KeyboardInterrupt:
print('interrupted!')
bot.send_message('Exit', channel_id='test-channel')

When I try to send message to my bot, it doesn't respond.

retrieve the username and role for the people speak to the robot

Is there a way to get the information regarding the one who is speaking to the robot?

For example, Bob speak in the general channel:

Bob:  @robot please what's the weather today?

can robot know it's Bob who is asking him, and Bob is with the role "user"?
I am asking because, sometimes, the robot is with many features, and may need to do role based permission control.

BR,Austin

webhook integration

I noticed the robot is pulling messages every second, while there is a webhook interface from RocketChat, shall we use webhook for better performance? What do you think the pros/cons between pulling and webhook?

Thanks,
Austin

ConnectTimeoutError

Is anyone else getting this error if the bot is left with no messages for a minute or so?

I dont think I had this issue in the past so i very well could be something on my end.

Full error from each thread

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 141, in _new_conn
(self.host, self.port), self.timeout, **extra_kw)
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 83, in create_connection
raise err
File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 73, in create_connection
sock.connect(sa)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 601, in urlopen
chunked=chunked)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 346, in _make_request
self._validate_conn(conn)
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 852, in _validate_conn
conn.connect()
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 284, in connect
conn = self._new_conn()
File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 146, in _new_conn
(self.host, self.timeout))
urllib3.exceptions.ConnectTimeoutError: (<urllib3.connection.VerifiedHTTPSConnection object at 0x7fd04937e128>, 'Connection to scrubedmydomain.com timed out. (connect timeout=30)')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 440, in send
timeout=timeout
File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='scrubedmydomain.com', port=443): Max retries exceeded with url: /api/v1/channels.list.joined (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x7fd04937e128>, 'Connection to scrubedmydomain.com timed out. (connect timeout=30)'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "dbot.py", line 181, in
bot.run()
File "dbot.py", line 150, in run
for channel in self.api.channels_list_joined().json().get('channels'):
File "/usr/local/lib/python3.6/dist-packages/rocketchat_API/rocketchat.py", line 278, in channels_list_joined
return self.__call_api_get('channels.list.joined', kwargs=kwargs)
File "/usr/local/lib/python3.6/dist-packages/rocketchat_API/rocketchat.py", line 55, in __call_api_get
timeout=self.timeout
File "/usr/lib/python3/dist-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/python3/dist-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 520, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 630, in send
r = adapter.send(request, **kwargs)
File "/usr/lib/python3/dist-packages/requests/adapters.py", line 496, in send
raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='scrubedmydomain.com', port=443): Max retries exceeded with url: /api/v1/channels.list.joined (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x7fd04937e128>, 'Connection to scrubedmydomain.com timed out. (connect timeout=30)'))

New RocketChat API changes break RocketChatBot

RocketChat recently changed their API (at least it seems so, by looking at the suddenly occuring error messages) and the bot is not working anymore:

KeyError('messages',)
KeyError('messages',)
KeyError('messages',)
KeyError('messages',)
KeyError('messages',)
KeyError('messages',)
KeyError('messages',)
KeyError('messages',)
Traceback (most recent call last):
  File "scripts/chatbot.py", line 160, in <module>
    main()
  File "scripts/chatbot.py", line 156, in main
    run()
  File "scripts/chatbot.py", line 47, in run
    bot.run()
  File "/home/off1user/.pyenv/versions/3.6.1/lib/python3.6/site-packages/RocketChatBot.py", line 135, in run
    for im in self.api.im_list().json().get('ims'):

Are there any plans to update this package? I am not sure I'll find time to jump in with a PR ๐Ÿ˜•

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.