示例#1
0
    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
示例#2
0
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())
示例#3
0
import os
sys.path.append(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

from discordWebhooks import Webhook, Attachment, Field

url = "https://ptb.discordapp.com/api/webhooks/246756716346212352/hztlLeSpjVaEKegZNivD6gvUA86wdRLmIx29_g2onRIGuaYD0pZfVor8LcNnhpSHnBtR"
wh = Webhook(url, "Text content", "Username",
             "https://www.facebook.com/favicon.ico")

at = Attachment(
    author_name="Author Name",
    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)
示例#4
0
import os
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

# Vars
namn=sys.argv[1]
torrent=sys.argv[2]
ratio=sys.argv[3]
seedTid=sys.argv[4]
uploaded=sys.argv[5]
size=sys.argv[6]
from discordWebhooks import Webhook, Attachment, Field

url = "" # Discord webhook url
wh = Webhook(url, " ", namn + " - Transmission Nuker")

at = Attachment(author_name = " ", color = "#ADFF2F", title = "[Torrent deleted!]")

field = Field("Who's torrent?", namn, False)
at.addField(field)
field = Field("Seeding time", seedTid, True)
at.addField(field)
field = Field("Ratio", ratio, True)
at.addField(field)
field = Field("Total size", size, True)
at.addField(field)
field = Field("Total uploaded", uploaded, True)
at.addField(field)
field = Field("Torrent name", torrent, False)
at.addField(field)

wh.addAttachment(at)
示例#5
0
import sys
import os
sys.path.append(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

from discordWebhooks import Webhook, Attachment, Field

url = "https://ptb.discordapp.com/api/webhooks/246756716346212352/hztlLeSpjVaEKegZNivD6gvUA86wdRLmIx29_g2onRIGuaYD0pZfVor8LcNnhpSHnBtR"
wh = Webhook(url, "Coucou tout le monde", "Pseudo")

at = Attachment(author_name="Derpolino",
                color="#ff0000",
                title="Discord webhooks")

field = Field("Version", "1.0", True)
at.addField(field)
field = Field("Last update", "27/10/2016", True)
at.addField(field)
field = Field("Changelog", "Initiale release !", False)
at.addField(field)

wh.addAttachment(at)

at = Attachment(author_name="Github", color="#0000ff", title="Hello world")
wh.addAttachment(at)

wh.post()
示例#6
0
    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