Exemple #1
0
    def __init__(self) -> None:
        log.info(f"Initializing bot as: {subprocess.check_output('id', text=True).rstrip()}")  # pylint: disable=unexpected-keyword-arg
        instance = config.INSTANCE
        self._active = True
        self._outgoing_msg_lock = threading.Lock()  # Used for rate limiting across multiple channels.
        self._db = Database()
        self._url_shortener = bitlyshortener.Shortener(
            tokens=[token.strip() for token in os.environ["BITLY_TOKENS"].strip().split(",")], max_cache_size=config.CACHE_MAXSIZE__BITLY_SHORTENER
        )
        self._publishers = [getattr(getattr(publishers, p), "Publisher")() for p in dir(publishers) if ((not p.startswith("_")) and (p in (instance.get("publish") or {})))]
        self._searchers = {s: getattr(getattr(searchers, s), "Searcher")() for s in dir(searchers) if ((not s.startswith("_")) and (s in (instance.get("publish") or {})))}

        # Setup miniirc
        log.debug("Initializing IRC client.")
        config.runtime.nick_casefold = instance["nick"].casefold()  # Prevents AttributeError if RPL_LOGGEDIN (900) is not sent by server, but is not always an accurate value.
        config.runtime.channel_topics = {}
        self._irc = miniirc.IRC(
            ip=instance["host"],
            port=instance["ssl_port"],
            nick=instance["nick"],
            channels=instance["feeds"],
            ssl=True,
            debug=log.info if instance.get("log", {}).get("irc") else False,
            ns_identity=(instance["nick"], os.environ["IRC_PASSWORD"]),
            connect_modes=instance.get("mode"),
            quit_message="",
            ping_interval=30,
        )
        log.info("Initialized IRC client.")
        self._setup_alerter()
        self._setup_channels()
        self._log_config()
        threading.Thread(target=self._search, name="Searcher").start()
        self._exit()  # Blocks.
Exemple #2
0
    def __init__(self) -> None:
        log.info('Initializing bot as: %s',
                 subprocess.check_output('id', text=True).rstrip())
        instance = config.INSTANCE
        self._outgoing_msg_lock = threading.Lock(
        )  # Used for rate limiting across multiple channels.
        self._db = Database()
        self._url_shortener = bitlyshortener.Shortener(
            tokens=[
                token.strip()
                for token in os.environ['BITLY_TOKENS'].strip().split(',')
            ],
            max_cache_size=config.BITLY_SHORTENER_MAX_CACHE_SIZE)

        # Setup miniirc
        log.debug('Initializing IRC client.')
        self._irc = miniirc.IRC(
            ip=instance['host'],
            port=instance['ssl_port'],
            nick=instance['nick'],
            channels=instance['feeds'],
            ssl=True,
            debug=False,
            ns_identity=(instance['nick'], os.environ['IRC_PASSWORD']),
            connect_modes=instance.get('mode'),
            quit_message='',
            ping_interval=30,
        )
        config.runtime.alert = lambda *args: _alert(self._irc, *args)
        log.info('Initialized IRC client.')

        self._setup_channels()
        self._log_config()
Exemple #3
0
    async def google(self, ctx, member: discord.Member = "", *args):
        try:
            mention = member.mention
        except:
            mention = ""

        url = str("https://lmgtfy.app/?q=" + '+'.join(args) + "&iie=1")

        if BITLY_API:
            shortener = bitlyshortener.Shortener(tokens=[BITLY_API], max_cache_size=256)
            short_url = shortener.shorten_urls([url])
            await ctx.send(mention + " " + short_url[0])

        else:
            await ctx.send(mention + " " + url)

        await ctx.message.delete()
Exemple #4
0
class ShourURL(Cog_Extension):
    with open('setting.json', 'r', encoding='utf8') as jfile:
        jdata = json.load(jfile)
    GUILD_ID = jdata['guild_id']
    tokens_pool = ['1182b14ca4b313491d3643c897a868e7877d87ca']
    shortener = bitlyshortener.Shortener(tokens=tokens_pool,
                                         max_cache_size=256)

    @cog_ext.cog_slash(name="shorturl",
                       description="Generate short url through bitlyapi.",
                       options=[
                           create_option(name="url",
                                         description="LongURL",
                                         option_type=3,
                                         required=True)
                       ],
                       guild_ids=GUILD_ID)
    async def _shorturl(self, ctx, url: str):
        long_urls = [url]
        try:
            await ctx.send(self.shortener.shorten_urls(long_urls)[0])
        except:
            await ctx.send("Fail")

    @commands.Cog.listener()
    async def on_message(self, msg):
        if msg.author != self.bot.user:
            pattern = r"((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*"
            longurl = re.match(pattern, msg.content)
            if longurl != None and self.shortener.usage() < 0.7:
                try:
                    # await msg.channel.send(longurl.group())
                    if len(longurl.group()) > 150 and len(msg.content) == len(
                            longurl.group()):
                        await msg.channel.send(
                            self.shortener.shorten_urls([longurl.group()])[0])
                        await msg.delete()
                except Exception as e:
                    print(e)
Exemple #5
0
import requests
import sys
import bitlyshortener
from config import *

if len(sys.argv) > 1:
    tokens_pool = [SHORTENER_API_BIT]
    shortener = bitlyshortener.Shortener(tokens=tokens_pool, max_cache_size=256)
    listUrl = [sys.argv[1]]
    GenUrl = shortener.shorten_urls(listUrl)
    if GenUrl:
        for GetUrl in GenUrl:
            print(GetUrl)
Exemple #6
0
import random

import psycopg2
import requests
import telebot
import config
import re
import bitlyshortener

# Setup short_maker_url
shortener = bitlyshortener.Shortener(tokens=config.shortcut_token, max_cache_size=256)

# Setup telegram bot
bot = telebot.TeleBot(config.telegram_TOKEN)


@bot.message_handler(commands=['start'])
def telegram_welcome(message):
    bot.send_message(message.chat.id,
                     "Добро пожаловать, {0.first_name}!\nЯ - <b>{1.first_name}</b>\nНапишите мне то, что вы ищете."
                     .format(message.from_user, bot.get_me()), parse_mode='html')


@bot.message_handler(content_types=['text'])
def send_to_telegram(message):
    """
    Telegram_bot_logic
    """
    correct_posts = take_posts_from_vk(message)  # get posts from vk.com

    try:  # for get random post from 'correct_posts'
from dotenv import load_dotenv

load_dotenv()

# get the environment values from the .env file
api_key = os.getenv('api_key')
username = os.getenv('username')
mobile_number = os.getenv('mobile_number')
# Initialize the Africas talking client using username and api_key
at.initialize(username, api_key)
# create a variable to reference the SMS client
sms = at.SMS
# Get the token(s) and create a shortener variable
token = os.getenv('bitly_token')
# create a variable to takes the token and returns a shortener object
shortener = bts.Shortener(tokens=[token], max_cache_size=256)

# create variables to hold urls to be scraped
business_daily = "https://www.businessdailyafrica.com/"
standard_daily = "https://www.standardmedia.co.ke/"
# create an empty list to hold the headlines and urls
message = []


# Create a function to scrape the top 3 headlines from news sources
def top_news(url):
    # get top articles on standard standard
    news_source = newspaper.build(url)
    top_articles = []

    for index in range(3):