Exemplo n.º 1
0
 def send_msg(self, title, desc, msg_title, msg):
     time.sleep(3)
     webhook = DiscordWebhooks(self.webhook_url)
     webhook.set_footer(text='    --By Hariprasath')
     webhook.set_content(title=title, description=desc)
     webhook.add_field(name=msg_title, value=msg)
     webhook.send()
Exemplo n.º 2
0
    def test_generic_embed_message(self):
        """
      Tests a generic message payload.
    """
        webhook = DiscordWebhooks('webhook_url')
        webhook.set_content(content='Montezuma', title='Best Cat Ever', description='Seriously', \
          url='http://github.com/JamesIves', color=0xF58CBA, timestamp='2018-11-09T04:10:42.039Z')

        expected_payload = \
          {
            'content': 'Montezuma',
            'embeds': [
                {
                  'title': 'Best Cat Ever',
                  'description': 'Seriously',
                  'url': 'http://github.com/JamesIves',
                  'color': 16092346,
                  'timestamp': '2018-11-09T04:10:42.039Z',
                  'fields': [],
                  'image': {},
                  'author': {},
                  'thumbnail': {},
                  'footer': {},
                }
              ]
            }

        self.assertEquals(webhook.format_payload(), expected_payload)
Exemplo n.º 3
0
    def broadcast_cl(self, cl):
        files_changed = self.get_changed_files(cl)
        file_exts = self.get_file_extensions(files_changed)
        file_ext_summary = self.summarize_exts(file_exts)

        change_type = 'unknown'
        if len(file_exts) > 0:
            change_type = self.get_file_category(file_exts[0][0])
        flavor = self.flavor_for_files(files_changed)

        p4_changes = subprocess.Popen('p4 describe -s -m 15 ' + cl,
                                      stdout=subprocess.PIPE,
                                      shell=True)
        desc = p4_changes.stdout.read().decode('ISO-8859-1')
        desc = re.sub(r'@[^ ]+ ', ' ', desc)
        desc = re.sub(r' by ', ' by @', desc)

        genMessage = DiscordWebhooks(self.general_webhook_url)
        self.fill_in_message(genMessage, change_type, file_ext_summary, flavor,
                             desc)
        if change_type == "code":
            message = DiscordWebhooks(self.code_webhook_url)
            self.fill_in_message(message, change_type, file_ext_summary,
                                 flavor, desc)
        elif change_type == "art":
            message = DiscordWebhooks(self.art_webhook_url)
            self.fill_in_message(message, change_type, file_ext_summary,
                                 flavor, desc)
        return
Exemplo n.º 4
0
    def getProductLink(self):
        webhook = DiscordWebhooks("enter discord webhook")
        response = self.s.get(self.link)
        responseSoup = BeautifulSoup(response.text, "lxml")

        productSelect = responseSoup.find("select", {"name": "id"})
        sizes = productSelect.findAll("option")

        productTitle = responseSoup.find("h1",
                                         {"class", "product-single__title"})

        img = responseSoup.find("img")
        imgURL = "http:" + img['src']

        webhookContent = ""

        for size in sizes:
            if "value" and not "disabled" in str(size):
                inStockSize = size.text.strip()
                variant = size["value"]
                print(inStockSize + " (" + variant + ")")
                webhookContent += f"{inStockSize} ([{variant}](http://www.kith.com/cart/{variant}:1))\n"

        webhook.set_content(title=productTitle.text.strip(),
                            description=(webhookContent),
                            url=self.link,
                            color=0xdc00ff)
        webhook.set_footer(
            text="oapi webhook",
            icon_url=
            'https://avatars1.githubusercontent.com/u/58406347?s=460&v=4')
        webhook.set_thumbnail(url=imgURL)
        webhook.send()
Exemplo n.º 5
0
    def test_set_footer(self):
        """
      Tests the set_footer method and ensures the data gets added to the payload.
    """
        webhook = DiscordWebhooks('webhook_url')
        webhook.set_footer(
            text='Footer',
            icon_url=
            'https://avatars1.githubusercontent.com/u/10888441?s=460&v=4')

        expected_payload = \
          {
            'embeds': [
                {
                  'fields': [],
                  'image': {},
                  'author': {},
                  'thumbnail': {},
                  'footer': {
                    'text': 'Footer',
                    'icon_url': 'https://avatars1.githubusercontent.com/u/10888441?s=460&v=4'
                  },
                }
              ]
            }

        self.assertEquals(webhook.format_payload(), expected_payload)
def send_test(textm):
    WEBHOOK_URL = webhook_url

    webhook = DiscordWebhooks(WEBHOOK_URL)
    # Attaches a footer
    webhook.set_footer(text='-- selenium bot')
    webhook.set_content(title='Test Message', description='sending log')
    webhook.add_field(name='log', value=textm)
    webhook.send()
    print("test message sent")
Exemplo n.º 7
0
def post():
    discord_text = get_changes()

    if discord_text != '':
        message = DiscordWebhooks(WebhookURL)
        message.set_content(color=0xc8702a,
                            description='`%s`' % (discord_text))
        message.set_author(name='Perforce Changelist Submit')
        message.set_footer(text='KaosSpectrum Perforce Commit Bot', ts=True)
        message.send()

    else:
        return
    def post_changes(self):
        """ Posts the changes to the Discord server via a webhook. """
        output = self.check_p4()
        payload = self.check_for_changes(output)

        if payload != '':
            message = DiscordWebhooks(self.webhook_url)
            message.set_content(color=0xc8702a, description='`%s`' % (payload))
            message.set_author(name='Perforce')
            message.set_footer(
                text='https://github.com/JamesIves/perforce-commit-discord-bot',
                ts=True)
            message.send()

        else:
            return
Exemplo n.º 9
0
    def on_status(self, status):
        if status.author.id_str in twitter_ids:
            # Get the time
            time_format = "%Y-%m-%d %H:%M:%S"
            timestamp_utc = status.created_at.replace(tzinfo=pytz.utc)
            timestamp_est = timestamp_utc.astimezone(pytz.timezone('America/New_York'))
            timestamp_str = timestamp_est.strftime(time_format)

            tweet_url = f'https://twitter.com/{status.author.screen_name}/status/{status.id}'

            message = f'{role_mentions[status.author.id_str]} New tweet from @{status.author.screen_name} at {timestamp_str}\n{tweet_url}'

            webhook = DiscordWebhooks(twitter_webhooks[status.author.id_str])
            webhook.set_content(content=message, url=tweet_url, color=0x00acee, description=status.text)
            webhook.set_author(name=f'{status.author.name} (@{status.author.screen_name})', url=f'https://twitter.com/{status.author.screen_name}', icon_url=status.author.profile_image_url)
            webhook.set_footer(text="Twitter", icon_url="https://cdn1.iconfinder.com/data/icons/iconza-circle-social/64/697029-twitter-512.png")
            webhook.send()
Exemplo n.º 10
0
    def test_set_author(self):
        """
      Tests the set_author method and ensures the data gets added to the payload.
    """
        webhook = DiscordWebhooks('webhook_url')
        webhook.set_content(content='Montezuma')
        webhook.set_author(
            name='James Ives',
            url='https://jamesiv.es',
            icon_url=
            'https://avatars1.githubusercontent.com/u/10888441?s=460&v=4')

        expected_payload = \
          {
            'content': 'Montezuma',
            'embeds': [
                {
                  'fields': [],
                  'image': {},
                  'author': {
                    'name': 'James Ives',
                    'url': 'https://jamesiv.es',
                    'icon_url': 'https://avatars1.githubusercontent.com/u/10888441?s=460&v=4'
                  },
                  'thumbnail': {},
                  'footer': {},
                }
              ]
            }

        self.assertEquals(webhook.format_payload(), expected_payload)
Exemplo n.º 11
0
def sendMessage(config, className, status):

    webhook = DiscordWebhooks(config['webhookURL'])
    webhook.set_footer(text='github.com/nxm')

    if status == 'success':
        print('{}Joined successfully!\n{}Sending notification to discord{}'.
              format(Colors.GREEN, Colors.BLUE, Colors.RESET))
        webhook.set_content(title='Class joined successfully!',
                            description=className)

    webhook.send()
Exemplo n.º 12
0
def post_changes():
  """ Posts the changes to the Discord server via a webhook.  """
  payload = check_for_changes()

  if payload != '':
    message = DiscordWebhooks(DISCORD_WEBHOOK_URL)
    message.set_content(color=0xc8702a, description='`%s`' % (payload))
    message.set_author(name=DISCORD_TITLE)
    message.send()

  else:
    return
Exemplo n.º 13
0
    def test_add_field(self):
        """
      Tests the set_field method and ensures the data gets added to the payload.
    """
        webhook = DiscordWebhooks('webhook_url')
        webhook.add_field(name='Field1', value='Value1', inline=True)
        webhook.add_field(name='Field2', value='Value2', inline=True)
        webhook.add_field(name='Field3', value='Value3', inline=False)

        # Inline should default to false
        webhook.add_field(name='Field4', value='Value4')

        expected_payload = \
          {
            'embeds': [
                {
                  'fields': [
                    {
                      'name': 'Field1',
                      'value': 'Value1',
                      'inline': True
                    },
                    {
                      'name': 'Field2',
                      'value': 'Value2',
                      'inline': True
                    },
                    {
                      'name': 'Field3',
                      'value': 'Value3',
                      'inline': False
                    },
                    {
                      'name': 'Field4',
                      'value': 'Value4',
                      'inline': False
                    },
                  ],
                  'image': {},
                  'author': {},
                  'thumbnail': {},
                  'footer': {},
                }
              ]
            }

        self.assertEquals(webhook.format_payload(), expected_payload)
Exemplo n.º 14
0
    def test_standard_message(self):
        """
      Tests a standard messgae payload with nothing but content.
    """
        webhook = DiscordWebhooks('webhook_url')
        webhook.set_content(content='Montezuma')

        expected_payload = {
            'content':
            'Montezuma',
            'embeds': [{
                'fields': [],
                'image': {},
                'author': {},
                'thumbnail': {},
                'footer': {},
            }]
        }

        self.assertEqual(webhook.format_payload(), expected_payload)
def send_webhook():
    voters = []
    max_votes = []
    data = get_vote_json()
    for x in data.items():
        for v in x[1]:
            voters.append(v)
    for x in voters:
        if x["nickname"] in [x["nickname"] for x in max_votes]:
            for u in max_votes:
                if u["nickname"] == x["nickname"]:
                    u["votes"] = str(int(x["votes"]) + int(u["votes"]))
        else:
            max_votes.append(x)
    message = "**Current Votes!** \U0001F389 \n\n"
    for v in max_votes:
        message += f"**User:** {v['nickname']} **Votes:** {v['votes']}\n"
    webhook = DiscordWebhooks(web_hook_url)
    webhook.set_content(content="**Vote Rewards**:\n"
                                "**12 = 500ARc\n15 = 750ARc\n18 = 1000ARc\n21 = 1250ARc**\n\n",
                        title='Click Me To Vote!',
                        description=message,
                        url='https://ark-servers.net/group/568/',
                        timestamp=str(datetime.now()),
                        color=0xF58CBA)
    webhook.send()
Exemplo n.º 16
0
class Discord:
    def __init__(self, config, webhook):
        self.data = discord_data()
        self.data.url = config['discord']['webhooks'][webhook]['url']
        self.data.name = config['discord']['webhooks'][webhook]['name']
        self.webhook = DiscordWebhooks(self.data.url)

    def send(self, message):
        if self.webhook != None:
            if message.url != None:
                self.webhook.set_content(color=message.color,
                                         title='%s' % (message.header),
                                         description='%s' % (message.content),
                                         url=message.url)
            else:
                self.webhook.set_content(color=message.color,
                                         title='%s' % (message.header),
                                         description='%s' % (message.content))
            self.webhook.set_author(name=message.user)
            self.webhook.set_footer(text=message.footer, ts=True)
            self.webhook.send()
        else:
            assert False, "Discord was not initilized"
Exemplo n.º 17
0
def clientthread(conn, addr):
    # Takes in messages from client to send to discord
    webhook = DiscordWebhooks(WEBHOOK_URL)
    while True:
        try:
            message = conn.recv(2048)
            if message:
                # Display message and send to discord
                webhook.set_content(content=message.decode('utf_8'))
                webhook.send()
                print("Me>\n\t" + message.decode('utf_8'))
            else:
                remove(conn)
        except:
            continue
Exemplo n.º 18
0
def webhook_call(url):
    print("Running SHU Episode Update")

    # Pull RSS feed, parse relevant content
    shu_feed = feedparser.parse("http://hoppedupgaming.hipcast.com/rss/super_hopped_up.xml")
    episode_info = shu_feed['entries'][0]
    ep_title = episode_info['title_detail']['value']
    ep_url = episode_info['media_comment']['href']
    ep_description = episode_info['content'][0]['value']

    # Setup content to post, create webhook connection, send post
    discord_content = "New SHU Podcast Episode!\n\n{}\n\n{}\n\n{}".format(ep_title, ep_url, ep_description)
    webhook = DiscordWebhooks(url)
    webhook.set_content(content=discord_content)
    webhook.send()
    print("Episode Update Successful")
    return
def score():
    webhook = DiscordWebhooks(web_hook_url)
    r = requests.get("https://api.sigmadraconis.games/scores")
    servers = r.json()["scores"]
    s = set([s["Server"] for s in servers])
    print(s)
    for s in s:
        ss = [x for x in servers if x["Server"] == s]
        print(ss)
        p = set([s["PlanetId"] for s in ss])
        print(p)
        d = ""
        webhook.set_content(content="\n", title=f"Scores for {s}")
        for p in p:
            sss = [x for x in ss if x["PlanetId"] == p]
            d += f"\n**Planet**: ***{p}***\n"
            for sss in sss:
                d += f"\n**Faction**: {sss['FactionName']}\n"
                d += f"**Score**: {sss['Points']}\n"
        print(d)
        webhook.set_content(content="",
                            title=f"Scores for **{s}**",
                            url="https://sigmadraconis.games/koth.html",
                            description=d,
                            timestamp=str(datetime.datetime.now()),
                            color=0xF58CBA)
        webhook.set_author(
            name="KOTH",
            icon_url=
            "https://cdn.discordapp.com/attachments/657771421564534807/689958406194200666/draconis_logo.png",
            url="https://sigmadraconis.games/koth.html")
        webhook.set_footer(
            text="https://sigmadraconis.games/koth.html",
            icon_url=
            "https://cdn.discordapp.com/attachments/657771421564534807/689958406194200666/draconis_logo.png"
        )
        webhook.set_thumbnail(
            url=
            "https://cdn.discordapp.com/attachments/657771421564534807/689958406194200666/draconis_logo.png"
        )
        webhook.send()
        time.sleep(5)
Exemplo n.º 20
0
import requests
import json
from discord_webhooks import DiscordWebhooks
import os

__j__ = json.loads(open("settings.json", 'r').read())

apiKey = __j__['apikey']  # https://isthereanydeal.com API key
webhook = DiscordWebhooks(__j__['webhook'])


class Game:
    def __init__(self, title, shop_name, buy_url, added):
        self.title = title
        self.shop_name = shop_name
        self.buy_url = buy_url
        self.added = added
        self.announce_msg = "`{}` Is now on {} For Free!\nGet it now: {}".format(
            self.title, self.shop_name, self.buy_url)


def get_games():
    r = requests.get('https://api.isthereanydeal.com/v01/deals/list/',
                     params={
                         'key': apiKey,
                         'sort': 'price:asc'
                     }).content.decode()
    j = json.loads(r)
    games = []
    for item in j['data']['list']:
        if item['price_new'] == 0 and not (
Exemplo n.º 21
0
def send_msg(class_name,link,status,date,start_time,end_time):

    WEBHOOK_URL = webhook_url 

    webhook = DiscordWebhooks(WEBHOOK_URL)
    

    if(status=="fetched"):

      webhook.set_content(title='Zoom Class',
                          description="Here's your Link :zap:")

      # Appends a field
      webhook.add_field(name='Class', value=class_name)
      webhook.add_field(name='Zoom link', value=link)
      webhook.add_field(name='Date', value=date)
      webhook.add_field(name='Start time', value=start_time)
      webhook.add_field(name='End time', value=end_time)
    


    elif(status=="noclass"):
      webhook.set_content(title='Zoom Class',
                          description="Class Link Not Found! Assuming no class :sunglasses:")

      # Appends a field
      webhook.add_field(name='Class', value=class_name)
      webhook.add_field(name='Date', value=date)
      webhook.add_field(name='Start time', value=start_time)
      webhook.add_field(name='End time', value=end_time)




    elif(status=="G-learn down"):
      webhook.set_content(title='G-learn Is Not Responding',
                          description="Link bot failed to fetch :boom:")

      # Appends a field
      webhook.add_field(name='Status', value=status)



    # Attaches a footer
    webhook.set_footer(text='-- Zoom Links')


    webhook.send()

    print("Sent message to discord")
def send_msg(username, follower_change, followers, unfollowers,
             followers_count, unfollowers_count, time, webhook_url):

    WEBHOOK_URL = webhook_url

    if followers == [] and unfollowers == []:
        print("No change in followers, so not sending message to discord")
        return

    if followers == []:
        followers = 'None'

    if unfollowers == []:
        unfollowers = 'None'

    webhook = DiscordWebhooks(WEBHOOK_URL)

    webhook.set_content(title='Report for %s' % (time),
                        description="Here's your report with :heart:")

    # Attaches a footer
    webhook.set_footer(text='-- Teja Swaroop')

    # Appends a field
    webhook.add_field(name='Username', value=username)
    webhook.add_field(name='Total follower change', value=follower_change)

    if unfollowers != 'None':
        webhook.add_field(name='People who unfollowed you (%d)' %
                          (unfollowers_count),
                          value=', '.join(unfollowers))
    else:
        webhook.add_field(name='People who unfollowed you (%d)' %
                          (unfollowers_count),
                          value=unfollowers)

    if followers != 'None':
        webhook.add_field(name='People who followed you (%d)' %
                          (followers_count),
                          value=', '.join(followers))
    else:
        webhook.add_field(name='People who followed you (%d)' %
                          (followers_count),
                          value=followers)

    webhook.send()

    print("Sent message to discord")
def DisIntro(webhook_url):
    webhook = DiscordWebhooks(webhook_url)
    webhook.set_content(
        title='Discord Bot Intro',
        description="This is going to be the channel to send message")
    webhook.set_footer(text='--ScarLet42')
def send_msg(insta_username, insta_password, username, follower_change,
             followers, unfollowers, followers_count, unfollowers_count, time,
             webhook_url, uforuf, fof):

    WEBHOOK_URL = webhook_url

    if followers == [] and unfollowers == []:
        print("No change in followers, so not sending message to discord")
        return

    if followers == []:
        followers = 'None'

    if unfollowers == []:
        unfollowers = 'None'

    webhook = DiscordWebhooks(WEBHOOK_URL)

    webhook.set_content(title='Report for %s' % (time),
                        description="Here's your report with :heart:")

    # Attaches a footer-
    webhook.set_footer(text='-- ScarLet42')

    # Appends a field
    webhook.add_field(name='Username', value=username)
    webhook.add_field(name='Total follower change', value=follower_change)

    if unfollowers != 'None':
        webhook.add_field(name='People who unfollowed you (%d)' %
                          (unfollowers_count),
                          value=', '.join(unfollowers))

    else:
        webhook.add_field(name='People who unfollowed you (%d)' %
                          (unfollowers_count),
                          value=unfollowers)

    if followers != 'None':
        webhook.add_field(name='People who followed you (%d)' %
                          (followers_count),
                          value=', '.join(followers))
    else:
        webhook.add_field(name='People who followed you (%d)' %
                          (followers_count),
                          value=followers)

    if (unfollowers != 'None' and uforuf == 'y'):

        bot = MyIGBot(insta_username, insta_password)
        for x in unfollowers:
            response = bot.unfollow(x)
            if (response == 200):
                print(x, "Unfollowed You On -", username)
                webhook.add_field(name='Unfollowed %s' % (x))
                print("Unfollowed", x)
            else:
                print(x, "Unfollowed You On -", username)
                print("Wasn't following ", x)

    if (followers != 'None' and fof == 'y'):
        bot = MyIGBot(insta_username, insta_password)
        for y in followers:
            response = bot.follow(y)
            if (response == 200):
                print("Followed back ", y)
                webhook.add_field(name='Followed Back %s' % (y))
            else:
                print("Already Following %s or some other error occured..." %
                      (y))

    webhook.send()

    print("Sent message to discord")
Exemplo n.º 25
0
from discord_webhooks import DiscordWebhooks
import discord

Bot = DiscordWebhooks(
    webhook_url=
    "https://discordapp.com/api/webhooks/591404084477558806/kfnSdUIe5RXtAzr7ROuXncZo3G4a-f9G9KPSfGGoISdCIfgYnvBxQ-dvaPa8SHhmwTaE"
)


def readToken():
    with open("token.txt", "r") as f:
        linea = f.readlines()
        return linea[0].strip()


token = readToken()
client = discord.Client()


@client.event
async def on_message(message):
    if message.content.find("!Hola") != -1:
        await message.channel.send("Hola pvto :v")
    if message.content.find("!Una de pubg") != -1:
        await message.channel.send("Bomba :v")
    if message.content.find("!Miembros") != -1:
        await message.channel.send(str(client.get_all_members()))
    if message.content.startswith("!Suma "):
        vals = message.content.split(" ")
        x = int(vals[1])
        y = int(vals[3])
Exemplo n.º 26
0
def job():
    url = 'add-your-webhook-url-here'
    newsapi = NewsApiClient(api_key='add-your-api-key-here')

    data = newsapi.get_top_headlines(language='en',country='in')

    if data['status'] == 'ok':
        ar1t = data['articles'][0]['title']
        ar1d = data['articles'][0]['url']
        ar1i = data['articles'][0]['urlToImage']

        ar2t = data['articles'][1]['title']
        ar2d = data['articles'][1]['url']
        ar2i = data['articles'][1]['urlToImage']

        ar3t = data['articles'][2]['title']
        ar3d = data['articles'][2]['url']
        ar3i = data['articles'][2]['urlToImage']

        ar4t = data['articles'][3]['title']
        ar4d = data['articles'][3]['url']
        ar4i = data['articles'][3]['urlToImage']

        ar5t = data['articles'][4]['title']
        ar5d = data['articles'][4]['url']
        ar5i = data['articles'][4]['urlToImage']

        cnews1 = DiscordWebhooks(url)
        cnews1.set_author(name="Today's top headlines")
        cnews1.set_content(title=ar1t,url=ar1d)
        cnews1.set_thumbnail(url=ar1i)

        cnews2 = DiscordWebhooks(url)
        cnews2.set_content(title=ar2t,url=ar2d)
        cnews2.set_thumbnail(url=ar2i)

        cnews3 = DiscordWebhooks(url)
        cnews3.set_content(title=ar3t,url=ar3d)
        cnews3.set_thumbnail(url=ar3i)

        cnews4 = DiscordWebhooks(url)
        cnews4.set_content(title=ar4t,url=ar4d)
        cnews4.set_thumbnail(url=ar4i)

        cnews5 = DiscordWebhooks(url)
        cnews5.set_content(title=ar5t,url=ar5d)
        cnews5.set_thumbnail(url=ar5i)
        cnews5.set_footer(text='Source - newsapi.org')

        cnews1.send()
        cnews2.send()
        cnews3.send()
        cnews4.send()
        cnews5.send()

    else:
        cnews = DiscordWebhooks(url)
        cnews.set_content(title="Sorry, we will be back soon with live news!")
        cnews.send()
Exemplo n.º 27
0
        )
        print()
        print(
            f'{swiftOutput}Successfully set name to {wantedName} using Swift Lite v{version}'
        )
        print(f'{swiftOutput}You sniped the name with request {i + 1} !')
        print(
            f'{swiftOutput}This request was most likely sent with account on line {int(i /20 ) + 1} in Accounts.txt'
        )

        if webhook_url == '':
            print(
                f'{swiftOutput}Did not find a webhook (or invalid), skipping!')
        else:
            try:
                webhook = DiscordWebhooks(webhook_url)
                webhook.set_content(
                    title='New Snipe!',
                    description=f'Succuessfully sniped name `{wantedName}`!',
                    color=0x72FF33)
                webhook.send()
                print(f'{swiftOutput}Sent message in #Snipes!')
            except:
                print(f'{swiftOutput}Seems like an invalid webhook ¯\_(ツ)_/¯')
        try:
            files = {
                'model': 'slim',
                'file': ('Skin.png', open('Skin.png', 'rb'))
            }
            response = session.put('https://api.mojang.com/user/profile/' +
                                   UUIDs[int(i / 20)] + '/skin',
Exemplo n.º 28
0
    def sendMessage(self, Message):
        if 'description' not in Message:
            raise ValueError('Discord messages requires a description')

        if 'content' not in Message:
            Message['content'] = ''

        if 'title' not in Message:
            Message['title'] = ''

        if 'color' not in Message:
            Message['color'] = 0xFFFFFF

        if 'author' not in Message:
            Message['author'] = {}
        if 'name' not in Message['author']:
            Message['author']['name'] = ''
        if 'url' not in Message['author']:
            Message['author']['url'] = ''
        if 'icon_url' not in Message['author']:
            Message['author']['icon_url'] = ''

        if 'footer' not in Message:
            Message['footer'] = {}
        if 'text' not in Message['footer']:
            Message['footer']['text'] = ''
        if 'icon_url' not in Message['footer']:
            Message['footer']['icon_url'] = ''

        message = DiscordWebhooks(self.webhook_url)
        message.set_content(color=Message['color'],
                            content=Message['content'],
                            description=Message['description'],
                            title=Message['title'])
        message.set_footer(text=Message['footer']['text'],
                           icon_url=Message['footer']['icon_url'])
        message.set_author(url=Message['author']['url'],
                           name=Message['author']['name'],
                           icon_url=Message['author']['icon_url'])
        if 'image' in Message:
            message.set_image(url=Message['image'])

        if not self.dry_run:
            message.send()
def send_msg(class_name, status, start_time, end_time):

    WEBHOOK_URL = webhook_url

    webhook = DiscordWebhooks(WEBHOOK_URL)
    # Attaches a footer
    webhook.set_footer(text='-- vaibdix')

    if (status == "joined"):

        webhook.set_content(title='Class Joined Succesfully',
                            description="Here's your report with :heart:")

        # Appends a field
        webhook.add_field(name='Class', value=class_name)
        webhook.add_field(name='Status', value=status)
        webhook.add_field(name='Joined at', value=start_time)
        webhook.add_field(name='Leaving at', value=end_time)

    elif (status == "left"):
        webhook.set_content(title='Class left Succesfully',
                            description="Here's your report with :heart:")

        # Appends a field
        webhook.add_field(name='Class', value=class_name)
        webhook.add_field(name='Status', value=status)
        webhook.add_field(name='Joined at', value=start_time)
        webhook.add_field(name='Left at', value=end_time)

    elif (status == "noclass"):
        webhook.set_content(
            title='Seems like no class today',
            description="No join button found! Assuming no class.")

        # Appends a field
        webhook.add_field(name='Class', value=class_name)
        webhook.add_field(name='Status', value=status)
        webhook.add_field(name='Expected Join time', value=status)
        webhook.add_field(name='Expected Leave time', value=end_time)

    webhook.send()

    print("Sent message to discord")
Exemplo n.º 30
0
def send_msg(class_name, status, start_time, end_time):
    webhook = DiscordWebhooks(webhook_url)
    # Attach the footer
    webhook.set_footer(text = '--Attender Bot')

    if status == "joined":
        webhook.set_content(title=f"{class_name} lecture has started",
                    description = ":heart:")
        #Put the Fields
        webhook.add_field(name = "Class", value = class_name)
        webhook.add_field(name = "Status", value = status)
        webhook.add_field(name = "Joined at", value = start_time)
        webhook.add_field(name = "Leaving at", value = end_time)
        
    elif status == "left":
        webhook.set_content(title=f"I left the {class_name} lecture",
                    description = "heart:")
        #Put the Fields
        webhook.add_field(name = "Class", value = class_name)
        webhook.add_field(name = "Status", value = status)
        webhook.add_field(name = "Joined at", value = start_time)
        webhook.add_field(name = "Left at", value = end_time)
        
    elif status == "noclass":
        webhook.set_content(title=f"today their is no class of {class_name}",
                    description = "heart:")
        #Put the Fields
        webhook.add_field(name = "Class", value = class_name)
        webhook.add_field(name = "Status", value = status)
        webhook.add_field(name = "Expected Join at", value = start_time)
        webhook.add_field(name = "Expected Leave at", value = end_time)
    webhook.send()
    print("Message Send")