Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def send_image(bot, event, url):
try:
image_id = yield from bot.upload_image(url)
except HTTPError:
bot.send_message(event.conv, "Error attempting to upload image.")
return
bot.send_message_segments(event.conv, [
hangups.ChatMessageSegment("Picture Message", segment_type=hangouts_pb2.SEGMENT_TYPE_LINE_BREAK)],
image_id=image_id)
def convert(self, source, slack):
if isinstance(source, str):
# Parse, then convert reparser.Segment to hangups.ChatMessageSegment.
segments = [ChatMessageSegment(seg.text, **seg.params) for seg in self.parse(source)]
else:
# We'll assume it's already a ChatMessageSegment list.
segments = source
formatted = ""
current = []
for seg in segments:
if seg.type_ == hangouts_pb2.SEGMENT_TYPE_LINE_BREAK:
# Insert closing tags for all current formatting, in reverse order.
for chars in reversed(current):
formatted += chars
# Start a new line.
formatted += "\n"
# Now reinsert the current formatting.
for chars in current:
formatted += chars
continue
if self.from_slack:
text = seg.text.replace(">", ">").replace("<", "<").replace("&", "&")
if seg.link_target:
if seg.link_target[0] == "@":
# User link, just replace with the plain username.
user = seg.link_target[1:]
if user in slack.users:
def _get_lookup_spec(identifier):
"""Return EntityLookupSpec from phone number, email address, or gaia ID."""
if identifier.startswith('+'):
return hangups.hangouts_pb2.EntityLookupSpec(
phone=identifier, create_offnetwork_gaia=True
)
elif '@' in identifier:
return hangups.hangouts_pb2.EntityLookupSpec(
email=identifier, create_offnetwork_gaia=True
)
else:
return hangups.hangouts_pb2.EntityLookupSpec(gaia_id=identifier)
.format("en" if is_history else "dis"))]
elif isinstance(event, hangups.RenameEvent):
action = True
title = event.new_name
segments = [HangoutsSegment("renamed the hangout to "),
HangoutsSegment(event.new_name, bold=True)]
elif isinstance(event, hangups.GroupLinkSharingModificationEvent):
action = True
is_shared = event.new_status == hangouts_pb2.GROUP_LINK_SHARING_STATUS_ON
segments = [HangoutsSegment("{}abled joining the hangout by link"
.format("en" if is_shared else "dis"))]
elif isinstance(event, hangups.HangoutEvent):
action = True
texts = {hangouts_pb2.HANGOUT_EVENT_TYPE_START: "started a call",
hangouts_pb2.HANGOUT_EVENT_TYPE_END: "ended the call",
hangouts_pb2.HANGOUT_EVENT_TYPE_JOIN: "joined the call",
hangouts_pb2.HANGOUT_EVENT_TYPE_LEAVE: "left the call"}
try:
segments = [HangoutsSegment(texts[event.event_type])]
except KeyError:
raise NotImplementedError
else:
raise NotImplementedError
if not isinstance(event, hangups.ChatMessageEvent):
text = immp.RichText(segments)
return immp.SentMessage(id_=event.id_,
channel=immp.Channel(hangouts, event.conversation_id),
at=event.timestamp,
text=text,
user=user,
action=action,
joined=joined,
async def set_presence(client, args):
request = hangups.hangouts_pb2.SetPresenceRequest(
request_header=client.get_request_header(),
status_message_setting=(
hangups.hangouts_pb2.StatusMessageSetting(
status_message=[
hangups.hangouts_pb2.ChatMessageSpec(
segment=[
hangups.hangouts_pb2.Segment(
type=hangups.hangouts_pb2.SEGMENT_TYPE_TEXT,
text='set up hangups',
formatting=hangups.hangouts_pb2.Formatting(
bold=False,
italic=False,
strikethrough=False,
underline=False,
),
),
def build_user_conversation_list(client):
"""Return UserList from initial contact data and an additional request.
The initial data contains the user's contacts, but there may be conversions
containing users that are not in the contacts. This function takes care of
requesting data for those users and constructing the UserList.
"""
# Retrieve recent conversations so we can preemptively look up their
# participants.
sync_recent_conversations_response = (
yield from client.sync_recent_conversations(
hangouts_pb2.SyncRecentConversationsRequest(
request_header=client.get_request_header(),
max_conversations=100,
max_events_per_conversation=1,
sync_filter=[hangouts_pb2.SYNC_FILTER_INBOX],
)
)
)
conv_states = sync_recent_conversations_response.conversation_state
sync_timestamp = parsers.from_timestamp(
# syncrecentconversations seems to return a sync_timestamp 4 minutes
# before the present. To prevent syncallnewevents later breaking
# requesting events older than what we already have, use
# current_server_time instead.
sync_recent_conversations_response.response_header.current_server_time
)
def on_membership_change(bot, event, command=""):
root = bot.get_config_option("slackrtm") or {}
syncs = [sync["channel"] for sync in root.get("syncs", []) if sync["hangout"] == event.conv_id]
if not syncs:
return
join = event.conv_event.type_ == hangouts_pb2.MEMBERSHIP_CHANGE_TYPE_JOIN
users = [event.conv.get_user(user_id) for user_id in event.conv_event.participant_ids]
if users == [event.user]:
text = "{} the hangout".format("joined" if join else "left")
else:
text = "{} {} {} the hangout".format("added" if join else "removed",
", ".join(user.full_name for user in users),
"to" if join else "from")
for team, channel in syncs:
for bridge in Base.bridges[team]:
if bridge.channel == channel:
config = bridge.applicable_configuration(event.conv_id)
passthru = {"original_request": {"message": text,
"image_id": None,
"segments": None,
"user": event.user},
"chatbridge": {"source_title": bot.conversations.get_name(event.conv_id),
"""Off-the-record toggle status."""
ENABLED = hangouts_pb2.OFF_THE_RECORD_TOGGLE_ENABLED
DISABLED = hangouts_pb2.OFF_THE_RECORD_TOGGLE_DISABLED
# new
UNKNOWN_OFF_THE_RECORD_TOGGLE = hangouts_pb2.OFF_THE_RECORD_TOGGLE_UNKNOWN
class ActiveClientState:
"""Active client state."""
NO_ACTIVE_CLIENT = hangouts_pb2.ACTIVE_CLIENT_STATE_NO_ACTIVE
IS_ACTIVE_CLIENT = hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE
OTHER_CLIENT_IS_ACTIVE = hangouts_pb2.ACTIVE_CLIENT_STATE_OTHER_ACTIVE
"""Focus devices."""
DESKTOP = hangouts_pb2.FOCUS_DEVICE_DESKTOP
MOBILE = hangouts_pb2.FOCUS_DEVICE_MOBILE
UNSPECIFIED = hangouts_pb2.FOCUS_DEVICE_UNSPECIFIED
class ConversationType:
"""Conversation type."""
STICKY_ONE_TO_ONE = hangouts_pb2.CONVERSATION_TYPE_ONE_TO_ONE
GROUP = hangouts_pb2.CONVERSATION_TYPE_GROUP
# new
UNKNOWN_TYPE = hangouts_pb2.CONVERSATION_TYPE_UNKNOWN
class ClientConversationView:
"""Conversation view."""
UNKNOWN_CONVERSATION_VIEW = hangouts_pb2.CONVERSATION_VIEW_UNKNOWN
INBOX_VIEW = hangouts_pb2.CONVERSATION_VIEW_INBOX
ARCHIVED_VIEW = hangouts_pb2.CONVERSATION_VIEW_ARCHIVED
class ClientNotificationLevel:
"""Notification level."""
UNKNOWN_NOTIFICATION = hangouts_pb2.NOTIFICATION_LEVEL_UNKNOWN
# Couldn't match the user's name to the message text.
pass
for attach in event._event.chat_message.message_content.attachment:
embed = attach.embed_item
if any(place in embed.type for place in
(hangouts_pb2.ITEM_TYPE_PLACE, hangouts_pb2.ITEM_TYPE_PLACE_V2)):
location = HangoutsLocation.from_embed(embed)
if str(text) == ("https://maps.google.com/maps?q={0},{1}"
.format(location.latitude, location.longitude)):
text = None
attachments.append(location)
elif hangouts_pb2.ITEM_TYPE_PLUS_PHOTO in embed.type:
attachments.append(await HangoutsFile.from_embed(hangouts, embed))
elif isinstance(event, hangups.MembershipChangeEvent):
action = True
is_join = event.type_ == hangouts_pb2.MEMBERSHIP_CHANGE_TYPE_JOIN
parts = [HangoutsUser.from_user(hangouts, hangouts._users.get_user(part_id))
for part_id in event.participant_ids]
if len(parts) == 1 and parts[0].id == user.id:
# Membership event is a user acting on themselves.
segments = [HangoutsSegment("{} the hangout"
.format("joined" if is_join else "left"))]
else:
segments = [HangoutsSegment("added " if is_join else "removed ")]
for part in parts:
link = "https://hangouts.google.com/chat/person/{}".format(part.id)
segments.append(HangoutsSegment(part.real_name, bold=True, link=link))
segments.append(HangoutsSegment(", "))
# Replace trailing comma.
segments[-1].text = " {} the hangout".format("to" if is_join else "from")
if is_join:
joined = parts