def on_status(self, status): """Called when a new status arrives""" colors = [ 0x7f0000, 0x535900, 0x40d9ff, 0x8c7399, 0xd97b6c, 0xf2ff40, 0x8fb6bf, 0x502d59, 0x66504d, 0x89b359, 0x00aaff, 0xd600e6, 0x401100, 0x44ff00, 0x1a2b33, 0xff00aa, 0xff8c40, 0x17330d, 0x0066bf, 0x33001b, 0xb39886, 0xbfffd0, 0x163a59, 0x8c235b, 0x8c5e00, 0x00733d, 0x000c59, 0xffbfd9, 0x4c3300, 0x36d98d, 0x3d3df2, 0x590018, 0xf2c200, 0x264d40, 0xc8bfff, 0xf23d6d, 0xd9c36c, 0x2db3aa, 0xb380ff, 0xff0022, 0x333226, 0x005c73, 0x7c29a6 ] data = status._json for dataDiscord in self.dataD: if data['user']['id_str'] not in dataDiscord['twitter_ids']: worthPosting = False if 'IncludeReplyToUser' in dataDiscord: #other Twitter user tweeting to your followed Twitter user if dataDiscord['IncludeReplyToUser'] == True: if data['in_reply_to_user_id_str'] in dataDiscord[ 'twitter_ids']: worthPosting = True else: worthPosting = True if 'IncludeUserReply' in dataDiscord: # your followed Twitter users tweeting to random Twitter users (relevant if you only want status updates/opt out of conversations) if dataDiscord['IncludeUserReply'] == False and data[ 'in_reply_to_user_id'] is not None: worthPosting = False if 'IncludeRetweet' in dataDiscord: # retweets... if dataDiscord['IncludeRetweet'] == False: if 'retweeted_status' in data: worthPosting = False #retweet if not worthPosting: continue for wh_url in dataDiscord['webhook_urls']: username = data['user']['screen_name'] icon_url = data['user']['profile_image_url'] text = '' if 'extended_tweet' in data: text = data['extended_tweet']['full_text'] else: text = data['text'] for url in data['entities']['urls']: if url['expanded_url'] == None: continue text = text.replace( url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) for userMention in data['entities']['user_mentions']: text = text.replace( '@%s' % userMention['screen_name'], '[@%s](https://twitter.com/%s)' % (userMention['screen_name'], userMention['screen_name'])) media_url = '' media_type = '' if 'extended_tweet' in data: if 'media' in data['extended_tweet']['entities']: for media in data['extended_tweet']['entities'][ 'media']: if media['type'] == 'photo': media_url = media['media_url'] if 'media' in data['entities']: for media in data['entities']['media']: if media['type'] == 'photo' and not media_url: media_url = media['media_url_https'] media_type = 'photo' if media['type'] == 'video': media_url = media['media_url_https'] media_type = 'photo' if media[ 'type'] == 'animated_gif' and media_type != "video": media_url = media['media_url_https'] media_type = 'photo' videoAlert = False if 'extended_entities' in data and 'media' in data[ 'extended_entities']: for media in data['extended_entities']['media']: if media['type'] == 'photo' and not media_url: media_url = media['media_url_https'] media_type = media['type'] if media['type'] == 'video': videoAlert = True media_type = media['type'] if media[ 'type'] == 'animated_gif' and media_type != "video": videoAlert = True media_type = 'gif' if videoAlert: text += " *[tweet has video]*" text = html.unescape(text) at = Embed( author_name=username, author_url="https://twitter.com/" + data['user']['screen_name'], author_icon=icon_url, color=random.choice(colors), description=text, media_url=media_url, media_type=media_type, title=data['user']['name'], url="https://twitter.com/" + data['user']['screen_name'] + "/status/" + str(data['id_str']), footer="Tweet created on", footer_icon= "https://cdn1.iconfinder.com/data/icons/iconza-circle-social/64/697029-twitter-512.png", timestamp=datetime.strptime( data['created_at'], '%a %b %d %H:%M:%S +0000 %Y').isoformat(' ')) print(strftime("[%Y-%m-%d %H:%M:%S]", gmtime()), data['user']['screen_name'], 'twittered.') #wh = Webhook(url=wh_url, username = username, icon_url=icon_url) wh = Webhook( url=wh_url ) #Use above if you have not set a default username and avatar for your webhook bot wh.addAttachment(at) if ('quoted_status' in data): text = data['quoted_status']['text'] for url in data['quoted_status']['entities']['urls']: if url['expanded_url'] == None: continue text = text.replace( url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) for userMention in data['quoted_status']['entities'][ 'user_mentions']: text = text.replace( '@%s' % userMention['screen_name'], '[@%s](https://twitter.com/%s)' % (userMention['screen_name'], userMention['screen_name'])) text = html.unescape(text) field = Field(data['quoted_status']['user']['screen_name'], text) at.addField(field) wh.post() return True
def on_status(self, status): """Called when a new status arrives""" colors = [ '#7f0000', '#535900', '#40d9ff', '#8c7399', '#d97b6c', '#f2ff40', '#8fb6bf', '#502d59', '#66504d', '#89b359', '#00aaff', '#d600e6', '#401100', '#44ff00', '#1a2b33', '#ff00aa', '#ff8c40', '#17330d', '#0066bf', '#33001b', '#b39886', '#bfffd0', '#163a59', '#8c235b', '#8c5e00', '#00733d', '#000c59', '#ffbfd9', '#4c3300', '#36d98d', '#3d3df2', '#590018', '#f2c200', '#264d40', '#c8bfff', '#f23d6d', '#d9c36c', '#2db3aa', '#b380ff', '#ff0022', '#333226', '#005c73', '#7c29a6' ] try: data = status._json with open('data.json') as data_file: dataDiscords = json.load(data_file) for dataDiscord in dataDiscords['Discord']: if data['user']['id_str'] in dataDiscord[ 'twitter_ids']: # filter out tweets from people replying to dota 2 personalities for wh_url in dataDiscord['webhook_urls']: wh = Webhook(url=wh_url) text = '' if 'extended_tweet' in data: text = data['extended_tweet']['full_text'] else: text = data['text'] for url in data['entities']['urls']: if url['expanded_url'] == None: continue text = text.replace( url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) for userMention in data['entities']['user_mentions']: text = text.replace( '@%s' % userMention['screen_name'], '[@%s](http://twitter.com/%s)' % (userMention['screen_name'], userMention['screen_name'])) media_url = '' if 'extended_tweet' in data: if 'media' in data['extended_tweet']['entities']: for media in data['extended_tweet'][ 'entities']['media']: if media['type'] == 'photo': media_url = media['media_url'] if 'media' in data['entities']: for media in data['entities']['media']: if media['type'] == 'photo': media_url = media['media_url'] at = Attachment( author_name=data['user']['screen_name'], author_icon=data['user']['profile_image_url'], color=random.choice(colors), pretext=text, image_url=media_url, title_link="https://twitter.com/" + data['user']['screen_name'] + "/status/" + str(data['id_str']), footer="Tweet created on", footer_icon= "https://cdn1.iconfinder.com/data/icons/iconza-circle-social/64/697029-twitter-512.png", ts=calendar.timegm( time.strptime(data['created_at'], '%a %b %d %H:%M:%S +0000 %Y'))) print(data['user']['screen_name'], ' twittered.') wh.addAttachment(at) if ('quoted_status' in data): text = data['quoted_status']['text'] for url in data['quoted_status']['entities'][ 'urls']: if url['expanded_url'] == None: continue text = text.replace( url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) for userMention in data['quoted_status'][ 'entities']['user_mentions']: text = text.replace( '@%s' % userMention['screen_name'], '[@%s](http://twitter.com/%s)' % (userMention['screen_name'], userMention['screen_name'])) field = Field( data['quoted_status']['user']['screen_name'], text) at.addField(field) wh.post() except: print('@@@@@@@@@@@@@@@@@@@@@@') print(data) print(type(data)) return True
author_icon="https://www.facebook.com/favicon.ico", color="#ffffff", pretext="pretext", title="title (with title_link)", title_link="http://github.com", image_url= "http://www.cekane.fr/wp-content/uploads/2015/10/googlelogosept12015.png", footer="footer (with footer_icon)", footer_icon="https://www.facebook.com/favicon.ico", ts="1000197000") field = Field("Field title", "Field value with Short (aligned)", True) at.addField(field) field = Field("Field title", "Field value with Short (aligned)", True) at.addField(field) field = Field("Field title", "Field value with Short (aligned)", True) at.addField(field) field = Field("Field title", "Field value without Short", False) at.addField(field) field = Field("Field title", "Field value without Short", False) at.addField(field) wh.addAttachment(at) at = Attachment(author_name="Second Attachment Author Name", color="#0000ff", title="Title") wh.addAttachment(at) wh.post()
def post_webhook(event): try: ticket = zenpy.tickets(id=event.ticket_id) requester = zenpy.users(id=ticket.requester_id) # Updater ID 0 is generally for Zendesk automation/non-user actions if event.updater_id > 0: updater = zenpy.users(id=event.updater_id) updater_name = updater.name updater_email = updater.email else: updater_name = "Zendesk System" updater_email = "*****@*****.**" # If the user has no Zendesk profile photo, use Gravatar if requester.photo is not None: avatar = requester.photo['content_url'] else: avatar = get_gravatar(requester.email) # Initialize an empty Discord Webhook object with the specified Webhook URL wh = Webhook(url, "", "", "") # Prepare the base ticket info embed (attachment) at = Attachment( author_name='{} ({})'.format(requester.name, requester.email), author_icon=avatar, color=status_color[ticket.status], title='[Ticket #{}] {}'.format(ticket.id, ticket.raw_subject), title_link="https://{}.zendesk.com/agent/#/tickets/{}".format( creds['subdomain'], ticket.id), footer=ticket.status.title(), ts=int(parser.parse(ticket.created_at).strftime( '%s'))) # TODO: always UTC, config timezone # If this is a new ticket, post it, ignore the rest. # This will only handle the first 'Create' child event # I have yet to see any more than one child event for new tickets for child in event.child_events: if child['event_type'] == 'Create': if first_run is True: wh = Webhook(url, "", "", "") else: wh = Webhook(url, "@here, New Ticket!", "", "") description = ticket.description # Strip any double newlines from the description while "\n\n" in description: description = description.replace("\n\n", "\n") field = Field("Description", ticket.description, False) at.addField(field) wh.addAttachment(at) wh.post() return wh.addAttachment(at) # Updater ID 0 is either Zendesk automation or non-user actions if int(event.updater_id) < 0: at = Attachment(color=status_color[ticket.status], footer="Zendesk System", footer_icon=default_icon, ts=int( parser.parse(event.created_at).strftime('%s'))) else: at = Attachment(color=status_color[ticket.status], footer='{} ({})'.format(updater_name, updater_email), footer_icon=get_gravatar(updater_email), ts=int( parser.parse(event.created_at).strftime('%s'))) for child in event.child_events: if child['event_type'] == 'Comment': for comment in zenpy.tickets.comments(ticket.id): if comment.id == child['id']: comment_body = comment.body while "\n\n" in comment_body: comment_body = comment_body.replace("\n\n", "\n") field = Field("Comment", comment_body, False) at.addField(field) elif child['event_type'] == 'Change': if 'status' not in child.keys(): if 'tags' in child.keys(): if len(child['removed_tags']) > 0: removed_tags = '~~`' removed_tags += '`~~\n~~`'.join( map(str, child['removed_tags'])) removed_tags += '`~~' field = Field("Tags Removed", '{}'.format(removed_tags), True) at.addField(field) if len(child['added_tags']) > 0: added_tags = '`' added_tags += '`\n`'.join( map(str, child['added_tags'])) added_tags += '`' field = Field("Tags Added", '{}'.format(added_tags), True) at.addField(field) elif 'assignee_id' in child.keys(): field = Field( "Assigned", '{}'.format(ticket.assignee.name, ticket.assignee.email), True) at.addField(field) elif 'type' in child.keys(): field = Field("Type Change", '`{}`'.format(child['type']), True) at.addField(field) else: logger.debug(child) else: field = Field( "Status Change", "{} to {}".format(child['previous_value'].title(), child['status'].title()), True) at.addField(field) else: logger.error("Event not handled") wh.addAttachment(at) i = 0 while i < 4: logger.debug('Posting to Discord') r = wh.post() i += 1 if r.text != 'ok': logger.error(r) logger.info('Discord webhook retry {}/3'.format(i)) else: break time.sleep(1) except Exception as e: if "RecordNotFound" in str(e): pass else: logger.error(traceback.print_exc())
def on_status(self, status): """Called when a new status arrives""" colors = ['#7f0000', '#535900', '#40d9ff', '#8c7399', '#d97b6c', '#f2ff40', '#8fb6bf', '#502d59', '#66504d', '#89b359', '#00aaff', '#d600e6', '#401100', '#44ff00', '#1a2b33', '#ff00aa', '#ff8c40', '#17330d', '#0066bf', '#33001b', '#b39886', '#bfffd0', '#163a59', '#8c235b', '#8c5e00', '#00733d', '#000c59', '#ffbfd9', '#4c3300', '#36d98d', '#3d3df2', '#590018', '#f2c200', '#264d40', '#c8bfff', '#f23d6d', '#d9c36c', '#2db3aa', '#b380ff', '#ff0022', '#333226', '#005c73', '#7c29a6'] data = status._json #print(data) with open('data.json') as data_file: dataD = json.load(data_file) for dataDiscord in dataD['Discord']: if 'IncludeReplyToUser' in dataDiscord: #other Twitter user tweeting to your followed Twitter user if dataDiscord['IncludeReplyToUser'] == False: if data['user']['id_str'] not in dataDiscord['twitter_ids']: #print('Random Twitter user tweeted to your followed twitter users') continue else: #if not specified: default behavior is not to include if data['user']['id_str'] not in dataDiscord['twitter_ids']: continue if 'IncludeUserReply' in dataDiscord: #your followed Twitter users tweeting to random Twitter users (relevant if you only want status updates/opt out of conversations) if dataDiscord['IncludeUserReply'] == False: if data['user']['id_str'] in dataDiscord['twitter_ids']: if data['in_reply_to_user_id'] is not None: if data['in_reply_to_user_id'] not in dataDiscord['twitter_ids']: if 'retweeted_status' not in data: #print('Your followed twitter users tweeted to someone else') continue if 'IncludeRetweet' in dataDiscord: #retweets... if dataDiscord['IncludeRetweet'] == False: if 'retweeted_status' in data: #print('This is a retweeted status') continue for wh_url in dataDiscord['webhook_urls']: wh = Webhook(url=wh_url) text = '' if 'extended_tweet' in data: text = data['extended_tweet']['full_text'] else: text = data['text'] for url in data['entities']['urls']: if url['expanded_url'] == None: continue text = text.replace(url['url'], "[%s](%s)" %(url['display_url'],url['expanded_url'])) for userMention in data['entities']['user_mentions']: text = text.replace('@%s' %userMention['screen_name'], '[@%s](http://twitter.com/%s)' %(userMention['screen_name'],userMention['screen_name'])) media_url = '' if 'extended_tweet' in data: if 'media' in data['extended_tweet']['entities']: for media in data['extended_tweet']['entities']['media']: if media['type'] == 'photo': media_url = media['media_url'] if 'media' in data['entities']: for media in data['entities']['media']: if media['type'] == 'photo': media_url = media['media_url'] at = Attachment(author_name=data['user']['screen_name'], author_icon=data['user']['profile_image_url'], color=random.choice(colors), pretext=text, image_url=media_url, title_link="https://twitter.com/" + data['user']['screen_name'] + "/status/" + str(data['id_str']), footer="Tweet created on", footer_icon="https://cdn1.iconfinder.com/data/icons/iconza-circle-social/64/697029-twitter-512.png", ts=calendar.timegm(time.strptime(data['created_at'], '%a %b %d %H:%M:%S +0000 %Y'))) print(strftime("[%Y-%m-%d %H:%M:%S]", gmtime()), data['user']['screen_name'], 'twittered.') wh.addAttachment(at) if ('quoted_status' in data): text = data['quoted_status']['text'] for url in data['quoted_status']['entities']['urls']: if url['expanded_url'] == None: continue text = text.replace(url['url'], "[%s](%s)" % (url['display_url'], url['expanded_url'])) for userMention in data['quoted_status']['entities']['user_mentions']: text = text.replace('@%s' %userMention['screen_name'], '[@%s](http://twitter.com/%s)' %(userMention['screen_name'],userMention['screen_name'])) field = Field(data['quoted_status']['user']['screen_name'], text) at.addField(field) wh.post() return True