Skip to content

Commit

Permalink
0.4.2-proposed (#54)
Browse files Browse the repository at this point in the history
Added the ability to pass attached files to the bot.
Added the ability to override built-in help.
Added the ability to disable message threading.
Added the ability to adjust logging level.
  • Loading branch information
ecoen66 authored Apr 24, 2024
1 parent cc5cd1e commit bf834cd
Show file tree
Hide file tree
Showing 4 changed files with 76 additions and 24 deletions.
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[bumpversion]
current_version = 0.4.1
current_version = 0.4.2
commit = True
tag = True

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@
test_suite="tests",
tests_require=test_requirements,
url="https://github.com/fbradyirl/webex_bot",
version="0.4.1",
version="0.4.2",
zip_safe=False,
)
61 changes: 41 additions & 20 deletions webex_bot/webex_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@
from webex_bot.websockets.webex_websocket_client import WebexWebsocketClient, DEFAULT_DEVICE_URL

log = logging.getLogger(__name__)
coloredlogs.install(level=os.getenv("LOG_LEVEL", "INFO"),
fmt='%(asctime)s [%(levelname)s] '
'[%(module)s.%(name)s.%(funcName)'
's]:%(lineno)s %(message)s')


class WebexBot(WebexWebsocketClient):
Expand All @@ -32,7 +28,10 @@ def __init__(self,
device_url=DEFAULT_DEVICE_URL,
include_demo_commands=False,
bot_name="Webex Bot",
bot_help_subtitle="Here are my available commands. Click one to begin."):
bot_help_subtitle="Here are my available commands. Click one to begin.",
threads=True,
help_command=None,
log_level="INFO"):
"""
Initialise WebexBot.
Expand All @@ -44,8 +43,16 @@ def __init__(self,
@param include_demo_commands: If True, any demo commands will be included.
@param bot_name: Your custom name for the bot.
@param bot_help_subtitle: Text to show in the help card.
@param threads: If True, respond to msg by creating a thread.
@param help_command: If None, use internal HelpCommand, otherwise override.
@param log_level: Set loggin level.
"""

coloredlogs.install(level=os.getenv("LOG_LEVEL", log_level),
fmt='%(asctime)s [%(levelname)s] '
'[%(module)s.%(name)s.%(funcName)'
's]:%(lineno)s %(message)s')
log.info("Registering bot with Webex cloud")
WebexWebsocketClient.__init__(self,
teams_bot_token,
Expand All @@ -58,27 +65,30 @@ def __init__(self,
# text and callback function
# By default supports 2 command, echo and help

self.help_command = HelpCommand(
bot_name=bot_name,
bot_help_subtitle=bot_help_subtitle,
bot_help_image=self.teams.people.me().avatar)
if help_command is None:
self.help_command = HelpCommand(
bot_name=bot_name,
bot_help_subtitle=bot_help_subtitle,
bot_help_image=self.teams.people.me().avatar)
self.help_command.commands = self.commands
# Set default help message
self.help_message = "Hello! I understand the following commands: \n"
else:
self.help_command = help_command
self.commands = {
self.help_command
}
if include_demo_commands:
self.add_command(EchoCommand())

self.help_command.commands = self.commands

self.card_callback_commands = {}
self.approved_users = approved_users
self.approved_domains = approved_domains
self.approved_rooms = approved_rooms
# Set default help message
self.help_message = "Hello! I understand the following commands: \n"
self.approval_parameters_check()
self.bot_display_name = ""
self.get_me_info()
self.threads = threads

@backoff.on_exception(backoff.expo, requests.exceptions.ConnectionError)
def get_me_info(self):
Expand Down Expand Up @@ -307,7 +317,7 @@ def do_reply(self, reply, room_id, user_email, reply_one_to_one, is_one_on_one_s
# If the Response lacks a roomId, set it to the incoming room
if not reply.roomId:
reply.roomId = room_id
if not reply.parentId and conv_target_id:
if not reply.parentId and conv_target_id and self.threads:
reply.parentId = conv_target_id
reply = reply.as_dict()
self.teams.messages.create(**reply)
Expand Down Expand Up @@ -351,14 +361,25 @@ def send_message_to_room_or_person(self,
quote_info(f"{user_email} I've messaged you 1-1. Please reply to me there.")
if reply_one_to_one:
if not is_one_on_one_space:
self.teams.messages.create(roomId=room_id,
markdown=default_move_to_one_to_one_heads_up,
if self.threads:
self.teams.messages.create(roomId=room_id,
markdown=default_move_to_one_to_one_heads_up,
parentId=conv_target_id)
else:
self.teams.messages.create(roomId=room_id,
markdown=default_move_to_one_to_one_heads_up)
if self.threads:
self.teams.messages.create(toPersonEmail=user_email,
markdown=reply,
parentId=conv_target_id)
self.teams.messages.create(toPersonEmail=user_email,
markdown=reply,
parentId=conv_target_id)
else:
self.teams.messages.create(toPersonEmail=user_email,
markdown=reply)
else:
self.teams.messages.create(roomId=room_id, markdown=reply, parentId=conv_target_id)
if self.threads:
self.teams.messages.create(roomId=room_id, markdown=reply, parentId=conv_target_id)
else:
self.teams.messages.create(roomId=room_id, markdown=reply)

def run_pre_card_load_reply(self, command, message, teams_message, activity):
"""
Expand Down
35 changes: 33 additions & 2 deletions webex_bot/websockets/webex_websocket_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,14 @@ def __init__(self,
self.on_message = on_message
self.on_card_action = on_card_action
self.websocket = None
self.share_id = None

def _process_incoming_websocket_message(self, msg):
"""
Handle websocket data.
:param msg: The raw websocket message
"""
logger.info(f"msg['data'] = {msg['data']}")
if msg['data']['eventType'] == 'conversation.activity':
activity = msg['data']['activity']
if activity['verb'] == 'post':
Expand All @@ -61,6 +63,31 @@ def _process_incoming_websocket_message(self, msg):
self._ack_message(message_base_64_id)
# Now process it with the handler
self.on_message(teams_message=webex_message, activity=activity)
elif activity['verb'] == 'share':
logger.debug(f"activity={activity}")
self.share_id = activity['id']
return
elif activity['verb'] == 'update':
logger.debug(f"activity={activity}")

object = activity['object']
if object['objectType'] == 'content' and object['contentCategory'] == 'documents':
if 'files' in object.keys():
for item in object['files']['items']:
if not item['malwareQuarantineState'] == 'safe':
return
else:
return
else:
return
message_base_64_id = self._get_base64_message_id(activity)
webex_message = self.teams.messages.get(message_base_64_id)
logger.debug(f"webex_message from message_base_64_id: {webex_message}")
if self.on_message:
# ack message first
self._ack_message(message_base_64_id)
# Now process it with the handler
self.on_message(teams_message=webex_message, activity=activity)
elif activity['verb'] == 'cardAction':
logger.debug(f"activity={activity}")

Expand All @@ -83,10 +110,14 @@ def _get_base64_message_id(self, activity):
@return: base 64 message id
"""
activity_id = activity['id']
logger.debug(f"activity verb=post. message id={activity_id}")
logger.debug(f"activity verb={activity['verb']}. message id={activity_id}")
conversation_url = activity['target']['url']
conv_target_id = activity['target']['id']
verb = "messages" if activity['verb'] == "post" else "attachment/actions"
verb = "messages" if activity['verb'] in ["post","update"] else "attachment/actions"
if activity['verb'] == "update" and self.share_id is not None:
activity_id = self.share_id
self.share_id = None
logger.debug(f"activity_id={activity_id}")
conversation_message_url = conversation_url.replace(f"conversations/{conv_target_id}",
f"{verb}/{activity_id}")
headers = {"Authorization": f"Bearer {self.access_token}"}
Expand Down

0 comments on commit bf834cd

Please sign in to comment.