Exemple #1
0
    async def bitly(self, ctx, *, link):
        try:
            access_token = os.environ.get("bitly_access_token")
            access_token = [access_token]

            shortener = Shortener(tokens=access_token, max_cache_size=8192)
            shortened_link = shortener.shorten_urls([link])

            embed = discord.Embed(color=self.bot.embed_color,
                                  title="→ URL Shortener")
            embed.add_field(name="• Long link:", inline=False, value=link)
            embed.add_field(name="• Shortened link:",
                            inline=False,
                            value=shortened_link[0])

            await ctx.send(embed=embed)

            logger.info(
                f"Utility | Sent Bitly: {ctx.author} | Long link: {link} | Shortened Link: {shortened_link[0]}"
            )
        except Exception:
            embed = discord.Embed(
                color=self.bot.embed_color,
                title="→ Invalid URL",
                description="• Please put a valid URL!"
                "\n• Example: `l!shortenlink https://google.com`")

            await ctx.send(embed=embed)
            ctx.command.reset_cooldown(ctx)
Exemple #2
0
async def shortener(short):
    """
    Shorten link using bit.ly API
    """
    if BITLY_TOKEN is not None:
        token = [f"{BITLY_TOKEN}"]
        reply = await short.get_reply_message()
        message = short.pattern_match.group(1)
        if message:
            pass
        elif reply:
            message = reply.text
        else:
            await short.edit("`Error! No URL given!`")
            return
        link_match = match(r"\bhttps?://.*\.\S+", message)
        if not link_match:
            await short.edit(
                "`Error! Please provide valid url!`\nexample: https://google.com"
            )
            return
        urls = [f"{message}"]
        bitly = Shortener(tokens=token, max_cache_size=8192)
        raw_output = bitly.shorten_urls(urls)
        string_output = f"{raw_output}"
        output = string_output.replace("['", "").replace("']", "")
        await short.edit(
            f"`Your link shortened successfully!`\nHere is your link {output}")
        if BOTLOG:
            await short.client.send_message(
                BOTLOG_CHATID, f"`#SHORTLINK \nThis Your Link!`\n {output}")
    else:
        await short.edit(
            "Set bit.ly API token first\nGet from [here](https://bitly.com/a/sign_up)"
        )
Exemple #3
0
    def post(self, request, *args, **kwargs):
        vendor = request.user.vendor

        form = SMSCampaignForm(request.data)

        if form.is_valid():
            campaign = form.save(commit=False)
            campaign.vendor = vendor
            campaign.save()
            campaign.to.add(*request.data['to'])

            URL = 'https://api.smsmode.com/http/1.6/'
            PATH_SEND_SMS = "sendSMS.do"

            sms_sent = 0

            tokens_pool = [os.environ.get('BITLY_API_KEY')]
            shortener = Shortener(tokens=tokens_pool, max_cache_size=8192)

            for customer in Customer.objects.filter(pk__in=request.data['to']):
                links = shortener.shorten_urls([
                    'https://app.kustomr.fr/welcome/{}-{}/{}'.format(
                        vendor.pk, slugify(vendor.store_name),
                        customer.token.token)
                ])
                final_url = (
                    URL + PATH_SEND_SMS + '?accessToken=' +
                    settings.SMSMODE_API_KEY + '&date_envoi=' +
                    datetime.strptime(
                        request.data['send_at'],
                        "%Y-%m-%d %H:%M").strftime('%d%m%Y-%H:%m') +
                    '&message=' + urllib.parse.quote_plus(
                        (request.data['content'] + '\nMon profil: {}'.format(
                            links[0])).encode('iso-8859-15')) + '&numero=' +
                    customer.phone + '&emetteur=' +
                    slugify(vendor.store_name).replace('_', '').upper()[:11] +
                    '&stop=1')
                r = requests.get(final_url)
                if r:
                    sms_sent += 1

            if sms_sent == 0:
                return Response(
                    {'message': 'Impossible de programmer la campagne SMS.'},
                    status=status.HTTP_400_BAD_REQUEST)
            campaign.sent = True
            campaign.save()
            return Response(
                {
                    'message':
                    'L\'envoi de {} SMS a été programmé.'.format(sms_sent)
                },
                status=status.HTTP_200_OK)

        else:
            print(form.errors)
            return Response(
                {'message': 'Impossible de valider le formulaire.'},
                status=status.HTTP_400_BAD_REQUEST)
Exemple #4
0
def linkshorten(linkbeforeshorten):
    tokens_pool = ['90e741cf3ceec9f9eb6b87b911ae42a007d4d6d3']  # Use your own.
    shortener = Shortener(tokens=tokens_pool, max_cache_size=8192)

    # Shorten to list

    urls = [linkbeforeshorten]
    return (shortener.shorten_urls(urls))
def shorten_url(url):
    shortener = Shortener(tokens=BITLY_ACCESS_TOKEN, max_cache_size=8192)

    if any('reddit' in s for s in url):
        link = shortener.shorten_urls(url)
    else:
        link = url
    return link
Exemple #6
0
async def bitly(_client, message):
    args = message.text.split(None, 1)
    shortener = Shortener(tokens=bitly_token, max_cache_size=8192)
    if len(args) == 1:
        await message.edit("Usage bitly (url)!")
        return
    if len(args) == 2:
        await message.edit("Processing")
        urls = [args[1]]
        shortlink = shortener.shorten_urls(urls)
        await message.edit("Here Your link\n{}".format(shortlink[0]), disable_web_page_preview=True)
 def __init__(self,url,title,reponame) :
      ThermalPrinter = adafruit_thermal_printer.get_printer_class(2.69)
      uart = serial.Serial("/dev/ttyS0", baudrate=19200, timeout=3000)
      self._printer = ThermalPrinter(uart)
      self._printer.warm_up()
      shortener = Shortener(tokens=tokens_pool, max_cache_size=8192)
      urls = [url]
      self._urlshort = shortener.shorten_urls(urls)
      self._last = url.rfind('/')
      self._n_issue = url[self._last+1:len(url)]
      qrcode_image = qrcode.make(self._urlshort[0])
      self._qrcode_logo = '/home/pi/qrcode.png'
      qrcode_image.save(self._qrcode_logo)
      self._title = title
      self._repository = reponame
Exemple #8
0
async def shorten(msg):
    if msg.get('text'):
        if msg['text'].startswith('/shorten'):
            text = msg['text'][9:]
            if not text:
                await bot.sendMessage(msg['chat']['id'],'*Uso:* `/shorten https://google.com` - _Encurta uma URL. ','Markdown',  reply_to_message_id=msg['message_id'])
            else:
                if not text.startswith('http://') or not text.startswith('https://'):
                    texto = 'https://' + text
                    try:
                        #sistema do pipy acima
                        tokens_pool = ["a001cef9d44ed8083ed4d952d475e98079e60577", ]
                        shortener = Shortener(tokens=tokens_pool, max_cache_size=8192)
                        urls = [texto]
                        a = shortener.shorten_urls(urls)
                        await bot.sendMessage(msg['chat']['id'], '*Link Encurtado:* {}'.format(a[0]), 'Markdown', reply_to_message_id=msg['message_id'])
                    except:
                        await bot.sendMessage(msg['chat']['id'], '`Não foi possivel encurtar seu link, tente enviando com http ou https, talves o serviço esteja offline.`', 'Markdown', reply_to_message_id=msg['message_id'])
            return True
Exemple #9
0
def palo():
    title = []
    link = []
    for art in articles:
        headline = art.h2.text
        perm = art.a.get('href')
        perm = paurl + perm
        title.append(headline)
        link.append(perm)
    return title, link

title, link = palo()

tokens_pool = ['cc1e818a5979fe47c9aa975f5c8228f5e68692b4']
shortener = Shortener(tokens=tokens_pool, max_cache_size=10000)
short_link = shortener.shorten_urls(link)

s_link = []
for s in short_link:
    bit = s.replace('j.mp', 'bit.ly')
    s_link.append(bit)


document.add_heading('{}'.format(topic).upper(), 0)


for n,t in enumerate(title):
    document.add_heading(t, level=1)
    document.add_paragraph(s_link[n])
    
date = datetime.date.today()
    "https://arxiv.org/abs/1902.01030v1",
    "https://arxiv.org/abs/1902.00916v1",
    "https://arxiv.org/abs/1902.00908v1",
    "https://arxiv.org/abs/1902.00771v1",
    "https://arxiv.org/abs/1902.00719v1",
    "https://arxiv.org/abs/1902.00685v1",
    "https://arxiv.org/abs/1902.00672v1",
    "https://arxiv.org/abs/1902.00659v1",
    "https://arxiv.org/abs/1902.00655v1",
    "https://arxiv.org/abs/1902.00626v1",
    "https://arxiv.org/abs/1902.00624v1",
    "https://arxiv.org/abs/1902.00604v1",
    "https://arxiv.org/abs/1902.00577v1",
    "https://arxiv.org/abs/1902.00541v1",
]

# URLs = ["https://j.mp/websniffer", "http://j.mp/2Bo2LVf", "http://bit.ly/2BombJQ", "https://cnn.it/2Ggb2ih"]

try:
    shortener = Shortener(tokens=TOKENS, max_cache_size=128)
    urls = random.sample(URLs, k=min(len(URLs), {"none": 0, "one": 1, "some": 3, "all": len(URLs)}["one"]))
    print(shortener.shorten_urls(urls))
    # print(shortener.usage())
    print(shortener.shorten_urls(urls))
    # print(shortener.usage())
    # print(shortener.shorten_urls_to_dict(urls[::-1]))

except Exception:
    time.sleep(0.01)  # Delay for longs to flush.
    raise
Exemple #11
0
async def link_direto(msg):
    try:
        chat_id = msg['chat']['id']
        chat_type = msg['chat']['type']
        texto = msg['text']
        tokens_pool = [
            "a001cef9d44ed8083ed4d952d475e98079e60577",
        ]
        shortener = Shortener(tokens=tokens_pool, max_cache_size=8192)
        if chat_type == 'supergroup':
            try:  # DOCUMENTOS
                if 'document' in msg.get(
                        'reply_to_message'
                ) and texto == '/link' or 'document' in msg.get(
                        'reply_to_message') and texto == 'link':
                    #if adm['user'] == True:
                    id_documento = msg.get(
                        'reply_to_message')['document']['file_id']
                    nome = msg.get('reply_to_message')['document']['file_name']
                    arquivo = await bot.getFile(id_documento)
                    tamanho = arquivo['file_size']
                    link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}"
                    try:
                        a = shortener.shorten_urls([link])
                        await bot.sendMessage(
                            chat_id,
                            f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}",
                            reply_to_message_id=msg['message_id'])
                    except:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`',
                            'Markdown',
                            reply_to_message_id=msg['message_id'])
            except Exception as e:
                pass

            try:  # IMAGENS
                if 'photo' in msg.get(
                        'reply_to_message'
                ) and texto == '/link' or 'photo' in msg.get(
                        'reply_to_message') and texto == 'link':
                    #if adm['user'] == True:
                    id_foto = msg.get(
                        'reply_to_message')['photo'][0]['file_id']
                    nome = 'imagem'
                    arquivo = await bot.getFile(id_foto)
                    tamanho = arquivo['file_size']
                    link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}"
                    try:
                        a = shortener.shorten_urls([link])
                        await bot.sendMessage(
                            chat_id,
                            f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}",
                            reply_to_message_id=msg['message_id'])
                    except:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`',
                            'Markdown',
                            reply_to_message_id=msg['message_id'])
            except Exception as e:
                pass

            try:  # AUDIOS
                if 'audio' in msg.get(
                        'reply_to_message'
                ) and texto == '/link' or 'audio' in msg.get(
                        'reply_to_message') and texto == 'link':
                    id_documento = msg.get(
                        'reply_to_message')['audio']['file_id']
                    nome = msg.get('reply_to_message')['audio']['title']
                    arquivo = await bot.getFile(id_documento)
                    tamanho = arquivo['file_size']
                    link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}"
                    try:
                        a = shortener.shorten_urls([link])
                        await bot.sendMessage(
                            chat_id,
                            f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}",
                            reply_to_message_id=msg['message_id'])
                    except:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`',
                            'Markdown',
                            reply_to_message_id=msg['message_id'])
            except Exception as e:
                pass

            try:  # VIDEOS
                if 'video' in msg.get(
                        'reply_to_message'
                ) and texto == '/link' or 'video' in msg.get(
                        'reply_to_message') and texto == 'link':
                    id_documento = msg.get(
                        'reply_to_message')['video']['file_id']
                    nome = 'video'
                    arquivo = await bot.getFile(id_documento)
                    tamanho = arquivo['file_size']
                    link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}"
                    try:
                        a = shortener.shorten_urls([link])
                        await bot.sendMessage(
                            chat_id,
                            f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nTamanho:{tamanho}\nLink:{a[0]}",
                            reply_to_message_id=msg['message_id'])
                    except:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`',
                            'Markdown',
                            reply_to_message_id=msg['message_id'])
            except Exception as e:
                pass

            try:  # VOZ
                if 'voice' in msg.get(
                        'reply_to_message'
                ) and texto == 'link' or 'voice' in msg.get(
                        'reply_to_message') and texto == '/link':
                    id_documento = msg.get(
                        'reply_to_message')['voice']['file_id']
                    nome = f"audio do {msg['from']['first_name']}"
                    arquivo = await bot.getFile(id_documento)
                    #tamanho = arquivo['file_size']
                    link = f"https://api.telegram.org/file/bot{token}/{arquivo['file_path']}"
                    try:
                        a = shortener.shorten_urls([link])
                        await bot.sendMessage(
                            chat_id,
                            f"🤖 Aqui está seu link direto.\nArquivo:{nome}\nLink:{a[0]}",
                            reply_to_message_id=msg['message_id'])
                    except:
                        await bot.sendMessage(
                            msg['chat']['id'],
                            '`Não foi possivel encurtar seu link, tente novamente, talves o serviço esteja offline.`',
                            'Markdown',
                            reply_to_message_id=msg['message_id'])
            except Exception as e:
                pass

    except Exception as e:
        pass