Пример #1
0
    def choose_team(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)
        
        chat_id = update.message.chat.id
        team = update.message.text

        if not re.match(f'^({HandlerHelpers.make_teams_regex(chat_id)})$', team):
            message = update.message.reply_text(f'Team "{team}" wasn\'t found, try again')
            Queue.add(message.chat.id, message.message_id)
            return RemoveTeam.CHOOSING_TEAM

        document = App.db.get_teams().find_one_and_delete({
            'chat_id': chat_id,
            'name': team,
        })
        if document:
            message = update.message.reply_text(
                f'Team "{team}" was successfully removed',
                reply_markup=ReplyKeyboardRemove(remove_keyboard=True),
            )
            Queue.add(message.chat.id, message.message_id)
        else:
            message = update.message.reply_text(
                f'Team "{team}" wasn\'t removed due to some errors, try again later',
                reply_markup=ReplyKeyboardRemove(remove_keyboard=True),
            )
            Queue.add(message.chat.id, message.message_id)

        Queue.clean(update.message.chat.id, timeout=30)
        return RemoveTeam.CHOOSING_END
Пример #2
0
 def __init__(self, keyword):
     self.keyword = keyword
     self.processed_comments = Queue(100)
     self.consecutive_timeouts = 0
     self.timeout_warn_threshold = 1
     self.pushshift_lag = 0
     self.pushshift_lag_checked = None
Пример #3
0
    def start(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        message = update.message.reply_text('Choose a team name')

        Queue.add(message.chat.id, message.message_id)

        return AddTeam.CHOOSING_NAME
Пример #4
0
    def __init__(self, user, no_post):
        log.info(f"Initializing reddit class: user={user} no_post={no_post}")
        self.no_post = no_post
        try:
            self.reddit = praw.Reddit(user, user_agent=static.USER_AGENT)
        except configparser.NoSectionError:
            log.error("User " + user + " not in praw.ini, aborting")
            raise ValueError
        static.ACCOUNT_NAME = self.reddit.user.me().name
        log.info("Logged into reddit as /u/" + static.ACCOUNT_NAME)

        self.processed_comments = Queue(100)
        self.consecutive_timeouts = 0
        self.timeout_warn_threshold = 1
Пример #5
0
    def mention(self, update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id
        team = update.message.text

        if not re.match(f'^({HandlerHelpers.make_teams_regex(chat_id)})$', team):
            message = update.message.reply_text(f'Team "{team}" wasn\'t found, try again')
            Queue.add(message.chat.id, message.message_id)
            return Mention.MENTION

        members = HandlerHelpers.get_team_members(chat_id, team)

        if members:
            update.message.reply_text(
                ' '.join(members),
                reply_markup=ReplyKeyboardRemove(remove_keyboard=True)
            )
        else:
            message = update.message.reply_text(
                'Members weren\'t found or something went wrong',
                reply_markup=ReplyKeyboardRemove(remove_keyboard=True)
            )
            Queue.add(message.chat.id, message.message_id)

        Queue.clean(update.message.chat.id, timeout=30)
        return Mention.CHOOSING_END
Пример #6
0
    def start(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id

        if not HandlerHelpers.check_teams_existence(update):
            return AddMembers.CHOOSING_END

        markup = ReplyKeyboardMarkup(map(lambda x: [x], HandlerHelpers.get_teams(chat_id)), one_time_keyboard=True)
        message = update.message.reply_text(
            f'Choose a team',
            reply_markup=markup
        )

        Queue.add(message.chat.id, message.message_id)
        return AddMembers.CHOOSING_TEAM
Пример #7
0
 def __init__(self, bot):
     ''' Initialize the MusicPlayer object '''
     self.id = bot.message.server.id
     self.__loop = asyncio.get_event_loop()
     self.chat = bot.message.channel
     self.sender = bot.message.author
     self.channel = bot.message.author.voice_channel
     self.bot = bot
     self.VC = None
     self.Player = None
     self.__queue = Queue()
     self.shutting_down = False
     self.allowed = ["file", "ytdl"]
     self.skipvotes = []
     self.paused = False
     self.oldmsg = None
     self.auto_dc = True
Пример #8
0
    def get(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id
        teams = HandlerHelpers.get_teams(chat_id)

        if len(teams) > 0:
            message = update.message.reply_text(', '.join(teams))
            Queue.add(message.chat.id, message.message_id, timeout=300)
        else:
            message = update.message.reply_text('No teams were found')
            Queue.add(message.chat.id, message.message_id)

        Queue.clean(update.message.chat.id)
        return GetTeams.GETTING_END
Пример #9
0
    def choose_name(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        name = update.message.text

        if re.match(r'^[0-9a-zа-яё._-]{2,16}$', name.lower(), re.IGNORECASE):
            if App.db.get_teams().find_one({
                'name': re.compile(f'^{name.lower()}$', re.IGNORECASE),
                'chat_id': update.message.chat.id
            }):
                message = update.message.reply_text(
                    f'Team "{name}" already exists, try another name'
                )
                Queue.add(message.chat.id, message.message_id)
                return AddTeam.CHOOSING_NAME
            else:
                App.db.get_teams().insert_one({
                    'name': name,
                    'chat_id': update.message.chat.id,
                    'members': [],
                })

                message = update.message.reply_text(
                    f'Team "{name}" was successfully created'
                )

                Queue.add(message.chat.id, message.message_id)
        else:
            message = update.message.reply_text(
                f'Team "{name}" wasn\'t created cause name contains incorrect symbols, try again'
            )

            Queue.add(message.chat.id, message.message_id)
            return AddTeam.CHOOSING_NAME

        Queue.clean(update.message.chat.id, timeout=30)
        return AddTeam.CHOOSING_END
Пример #10
0
    def choose_members(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id
        team = context.user_data['team']

        # set is used to remove duplicated
        members = list(
            set(filter(
                lambda x: re.match(r'^@[0-9a-z._-]{5,32}$', x.lower(), re.IGNORECASE) and x not in HandlerHelpers.get_team_members(chat_id, team),
                update.message.text.split(' ')
            ))
        )

        if members:
            App.db.get_teams().find_one_and_update({
                'chat_id': chat_id,
                'name': team,
            }, {
                '$push': {
                    'members': {
                        '$each': members,
                    },
                },
            })

            message = update.message.reply_text(
                f'Greeting new members of the "{team}" team: {" ".join(members)}'
            )

            Queue.add(message.chat.id, message.message_id)
        else:
            message = update.message.reply_text(
                f'No members were added to the team "{team}"'
            )

            Queue.add(message.chat.id, message.message_id)

        Queue.clean(update.message.chat.id, timeout=30)
        return AddMembers.CHOOSING_END
Пример #11
0
    def choose_members(self, update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id
        team = context.user_data['team']

        members = list(
            filter(
                lambda x: x.startswith('@') and x in
                HandlerHelpers.get_team_members(chat_id, team),
                update.message.text.split(' ')))

        if members:
            App.db.get_teams().find_one_and_update(
                {
                    'chat_id': chat_id,
                    'name': team,
                }, {
                    '$pull': {
                        'members': {
                            '$in': members,
                        },
                    },
                })

            message = update.message.reply_text(
                f'Members who were removed from "{team}" team: {" ".join(members)}'
            )
            Queue.add(message.chat.id, message.message_id)
        else:
            message = update.message.reply_text(
                f'No members were removed from the team "{team}"')
            Queue.add(message.chat.id, message.message_id)

        Queue.clean(update.message.chat.id, timeout=30)
        return RemoveMembers.CHOOSING_END
Пример #12
0
def printerSimulation(numSeconds, ppm: int):
    printer = Printer(ppm)
    printQueue = Queue()
    waitingTimes = []

    for currentSecond in range(numSeconds):
        if newPrintTask():
            task = Task(currentSecond)
            printQueue.enqueue(task)

        if (not printer.isBusy()) and (not printQueue.isEmpty()):
            nextTask = printQueue.dequeue()
            waitingTimes.append(nextTask.waitTime(currentSecond))
            printer.next(nextTask)

        printer.tick()

    averageWaitingTime = sum(waitingTimes) / len(waitingTimes)

    print(
        "Average waiting time is {:.^14.2f} secs and {:.>5d} tasks remaining".
        format(averageWaitingTime, printQueue.size()))
Пример #13
0
    def choose_team(self, update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id
        context.user_data['team'] = team = update.message.text

        if not re.match(f'^({HandlerHelpers.make_teams_regex(chat_id)})$',
                        team):
            message = update.message.reply_text(
                f'Team "{team}" wasn\'t found, try again')
            Queue.add(message.chat.id, message.message_id)
            return RemoveMembers.CHOOSING_TEAM

        message = update.message.reply_text(
            f'Now, send user @logins separated by space to remove them from the team "{team}" (with leading @)',
            reply_markup=ReplyKeyboardRemove(remove_keyboard=True))
        Queue.add(message.chat.id, message.message_id)

        return RemoveMembers.CHOOSING_MEMBERS
Пример #14
0
    def choose_team(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id
        context.user_data['old_team_name'] = old_team_name = update.message.text

        if not re.match(f'^({HandlerHelpers.make_teams_regex(chat_id)})$', old_team_name):
            message = update.message.reply_text(f'Team "{old_team_name}" wasn\'t found, try again')
            Queue.add(message.chat.id, message.message_id)
            return RenameTeam.CHOOSING_TEAM

        message = update.message.reply_text(
            f'Now send new name for the team "{old_team_name}"',
            reply_markup=ReplyKeyboardRemove(remove_keyboard=True),
        )

        Queue.add(message.chat.id, message.message_id)

        return RenameTeam.CHOOSING_NEW_NAME
Пример #15
0
    def help(self, update: Update, context: CallbackContext):
        timeout = 120
        Queue.add(update.message.chat.id,
                  update.message.message_id,
                  timeout=timeout)

        message = update.message.reply_text(
            '*Commands for admins:*\n'
            '/addteam – Add team\n'
            '/addmembers – Add members to the chosen team\n'
            '/removeteam – Remove team\n'
            '/removemembers – Remove members from the chosen team\n'
            '/renameteam – Rename team to the new given name\n'
            '\n'
            '*Commands for all members:*\n'
            '/mention – Choose a team to mention\n'
            '/getteams – List of all added teams\n'
            '/help – Get some basic info about bot and commands\n'
            '/cancel – Prevent any running command\n',
            parse_mode=ParseMode.MARKDOWN)

        Queue.add(message.chat.id, message.message_id, timeout=timeout)
        Queue.clean(update.message.chat.id)
Пример #16
0
class Reddit:
    def __init__(self, user, no_post):
        log.info(f"Initializing reddit class: user={user} no_post={no_post}")
        self.no_post = no_post
        try:
            self.reddit = praw.Reddit(user, user_agent=static.USER_AGENT)
        except configparser.NoSectionError:
            log.error("User " + user + " not in praw.ini, aborting")
            raise ValueError
        static.ACCOUNT_NAME = self.reddit.user.me().name
        log.info("Logged into reddit as /u/" + static.ACCOUNT_NAME)

        self.processed_comments = Queue(100)
        self.consecutive_timeouts = 0
        self.timeout_warn_threshold = 1

    def run_function(self, function, arguments):
        output = None
        result = None
        try:
            output = function(*arguments)
        except praw.exceptions.APIException as err:
            for return_type in ReturnType:
                if err.error_type == return_type.name:
                    result = return_type
                    break
            if result is None:
                raise
        except prawcore.exceptions.Forbidden:
            result = ReturnType.FORBIDDEN
        except IndexError:
            result = ReturnType.QUARANTINED

        if result is None:
            result = ReturnType.SUCCESS
        return output, result

    def is_message(self, item):
        return isinstance(item, praw.models.Message)

    def get_messages(self, count=500):
        log.debug("Fetching unread messages")
        message_list = []
        for message in self.reddit.inbox.unread(limit=count):
            message_list.append(message)
        return message_list

    def reply_message(self, message, body):
        log.debug(f"Replying to message: {message.id}")
        if self.no_post:
            log.info(body)
            return ReturnType.SUCCESS
        else:
            output, result = self.run_function(message.reply, [body])
            return result

    def mark_read(self, message):
        log.debug(f"Marking message as read: {message.id}")
        if not self.no_post:
            message.mark_read()

    def reply_comment(self, comment, body):
        log.debug(f"Replying to message: {comment.id}")
        if self.no_post:
            log.info(body)
            return "xxxxxx", ReturnType.SUCCESS
        else:
            output, result = self.run_function(comment.reply, [body])
            if output is not None:
                return output.id, result
            else:
                return None, result

    def send_message(self, username, subject, body):
        log.debug(f"Sending message to u/{username}")
        if self.no_post:
            log.info(body)
            return ReturnType.SUCCESS
        else:
            redditor = self.reddit.redditor(username)
            output, result = self.run_function(redditor.message,
                                               [subject, body])
            return result

    def get_comment(self, comment_id):
        log.debug(f"Fetching comment by id: {comment_id}")
        if comment_id == "xxxxxx":
            return None
        else:
            return self.reddit.comment(comment_id)

    def edit_comment(self, body, comment=None, comment_id=None):
        if comment is None:
            comment = self.get_comment(comment_id)
        log.debug(f"Editing comment: {comment.id}")

        if self.no_post:
            log.info(body)
        else:
            output, result = self.run_function(comment.edit, [body])
            return result

    def delete_comment(self, comment):
        log.debug(f"Deleting comment: {comment.id}")
        if not self.no_post:
            try:
                comment.delete()
            except Exception:
                log.warning(f"Error deleting comment: {comment.comment_id}")
                log.warning(traceback.format_exc())
                return False
        return True

    def quarantine_opt_in(self, subreddit_name):
        log.debug(f"Opting in to subreddit: {subreddit_name}")
        if not self.no_post:
            try:
                self.reddit.subreddit(subreddit_name).quaran.opt_in()
            except Exception:
                log.warning(f"Error opting in to subreddit: {subreddit_name}")
                log.warning(traceback.format_exc())
                return False
        return True

    def get_keyword_comments(self, keyword, last_seen):
        if not len(self.processed_comments.list):
            last_seen = last_seen + timedelta(seconds=1)

        log.debug(
            f"Fetching comments for keyword: {keyword} : {utils.get_datetime_string(last_seen)}"
        )
        url = f"https://api.pushshift.io/reddit/comment/search?q={keyword}&limit=100&sort=desc"
        try:
            json = requests.get(url,
                                headers={'User-Agent': static.USER_AGENT},
                                timeout=10)
            if json.status_code != 200:
                log.warning(
                    f"Could not parse data for search term: {keyword} status: {str(json.status_code)}"
                )
                return []
            comments = json.json()['data']

            if self.timeout_warn_threshold > 1:
                log.warning(
                    f"Recovered from timeouts after {self.consecutive_timeouts} attempts"
                )

            self.consecutive_timeouts = 0
            self.timeout_warn_threshold = 1

        except requests.exceptions.ReadTimeout:
            self.consecutive_timeouts += 1
            if self.consecutive_timeouts >= pow(self.timeout_warn_threshold,
                                                2) * 5:
                log.warning(
                    f"{self.consecutive_timeouts} consecutive timeouts for search term: {keyword}"
                )
                self.timeout_warn_threshold += 1
            return []

        except Exception as err:
            log.warning(f"Could not parse data for search term: {keyword}")
            log.warning(traceback.format_exc())
            return []

        if not len(comments):
            log.warning(f"No comments found for search term: {keyword}")
            return []

        result_comments = []
        for comment in comments:
            date_time = utils.datetime_from_timestamp(comment['created_utc'])
            if last_seen > date_time:
                break

            if not self.processed_comments.contains(comment['id']):
                result_comments.append(comment)

        log.debug(f"Found comments: {len(result_comments)}")
        return result_comments

    def mark_keyword_comment_processed(self, comment_id):
        self.processed_comments.put(comment_id)
Пример #17
0
    def choose_new_name(self, update: Update, context: CallbackContext):
        Queue.add(update.message.chat.id, update.message.message_id)

        chat_id = update.message.chat.id
        new_team_name = update.message.text
        old_team_name = context.user_data['old_team_name']

        if App.db.get_teams().find_one({'chat_id': chat_id, 'name': new_team_name}):
            message = update.message.reply_text(
                f'Team wasn\'t renamed, cause "{new_team_name}" already exists, send new name for team "{old_team_name}" again',
            )
            Queue.add(message.chat.id, message.message_id)
            return RenameTeam.CHOOSING_NEW_NAME

        if not re.match(r'^[0-9a-zа-яё._-]{2,16}$', new_team_name.lower(), re.IGNORECASE):
            message = update.message.reply_text(
                f'Team wasn\'t renamed, cause name "{new_team_name}" contains incorrect symbols, try again',
            )
            Queue.add(message.chat.id, message.message_id)
            return RenameTeam.CHOOSING_NEW_NAME

        if App.db.get_teams().find_one_and_update({'chat_id': chat_id, 'name': old_team_name}, {'$set': {'name': new_team_name}}):
            message = update.message.reply_text(
                f'Team "{old_team_name}" was renamed to "{new_team_name}"'
            )
            Queue.add(message.chat.id, message.message_id)
        else:
            message = update.message.reply_text(
                f'Team "{old_team_name}" wasn\'t renamed to "{new_team_name}" due to some errors, try again later',
                reply_markup=ReplyKeyboardRemove(remove_keyboard=True),
            )
            Queue.add(message.chat.id, message.message_id)

        Queue.clean(update.message.chat.id, timeout=30)
        return RenameTeam.CHOOSING_END
Пример #18
0
class RedditKeywordWatcher:
    def __init__(self, keyword):
        self.keyword = keyword
        self.processed_comments = Queue(100)
        self.consecutive_timeouts = 0
        self.timeout_warn_threshold = 1
        self.pushshift_lag = 0
        self.pushshift_lag_checked = None

    def get(self):
        last_seen = utils.get_last_seen(self.keyword)
        log.debug(
            f"Fetching comments for keyword: {self.keyword} : {last_seen}")
        url = f"https://api.pushshift.io/reddit/comment/search?q={self.keyword}&limit=100&sort=desc&fields=created_utc,id"
        lag_url = "https://api.pushshift.io/reddit/comment/search?limit=1&sort=desc"
        try:
            json = requests.get(url,
                                headers={'User-Agent': config.USER_AGENT},
                                timeout=10)
            if json.status_code != 200:
                log.warning(
                    f"Could not parse data for search term: {self.keyword} status: {str(json.status_code)}"
                )
                return []
            comments = json.json()['data']

            if self.pushshift_lag_checked is None or \
              utils.datetime_now() - timedelta(minutes=10) > self.pushshift_lag_checked:
                log.debug("Updating pushshift comment lag")
                json = requests.get(lag_url,
                                    headers={'User-Agent': config.USER_AGENT},
                                    timeout=10)
                if json.status_code == 200:
                    comment_created = utils.datetime_from_timestamp(
                        json.json()['data'][0]['created_utc'])
                    self.pushshift_lag = round(
                        (utils.datetime_now() - comment_created).seconds / 60,
                        0)
                    self.pushshift_lag_checked = utils.datetime_now()

            if self.timeout_warn_threshold > 1:
                log.warning(
                    f"Recovered from timeouts after {self.consecutive_timeouts} attempts"
                )

            self.consecutive_timeouts = 0
            self.timeout_warn_threshold = 1

        except requests.exceptions.ReadTimeout:
            self.consecutive_timeouts += 1
            if self.consecutive_timeouts >= pow(self.timeout_warn_threshold,
                                                2) * 5:
                log.warning(
                    f"{self.consecutive_timeouts} consecutive timeouts for search term: {self.keyword}"
                )
                self.timeout_warn_threshold += 1
            return []

        except Exception as err:
            log.warning(
                f"Could not parse data for search term: {self.keyword}")
            log.warning(traceback.format_exc())
            return []

        if not len(comments):
            log.warning(f"No comments found for search term: {self.keyword}")
            return []

        result_comments = []
        for comment in comments:
            date_time = utils.datetime_from_timestamp(comment['created_utc'])
            if last_seen > date_time:
                break

            if not self.processed_comments.contains(comment['id']):
                result_comments.append(comment)

        return result_comments

    def set_processed(self, comment_id):
        self.processed_comments.put(comment_id)
Пример #19
0
import msvcrt # Windows-only non-blocking input. Universal would need a lot more things
import random
from classes.espresso import Espresso
from classes.queue import Queue
from classes.coffeeenum import CoffeeEnum
from classes.order import Order

# Launch the machine
num_engineers = 1705
chance_superbusy = 25 # percent
max_time_superbusy = 120 # minutes
espresso_machine = Espresso(num_engineers, chance_superbusy, max_time_superbusy)
espresso_machine.start()

# Setup a few things
queue = Queue()
queue_id = 0
coffee_name = CoffeeEnum()
superbusy = False

# Run the show!
espresso_machine.display_coffee_choices()
while True:
	if queue.has_orders() and espresso_machine.is_ready():
		espresso_machine.brew(queue.get_next(), queue)
	
	# Read input to get new orders and enter superbusy mode
	if msvcrt.kbhit():
		# There's a chance the engineer is superbusy!
		if random.randrange(0, 100) < chance_superbusy:
			print("By surprise, you are now superbusy!")
Пример #20
0
import json
from classes.logger import Logger
from classes.cart import Cart
from classes.captcha import Captcha
from classes.queue import Queue
from classes.tools import Tools



if __name__ == '__main__':
    session = requests.Session()
    lock = threading.Lock()
    tools = Tools()
    config = tools.load('config/config.json')
    log = Logger().log
    q = Queue()
    cart = Cart(session, lock)

    api_key = config['key']['2captcha']
    captcha = Captcha(api_key)
    queue = Queue()

    if 'true' in config['settings']['browser']['US'].lower() and 'true' in config['settings']['browser']['EU'].lower():
        log('You have both regions selected - please select only one.','error')
        exit()

    if 'true' in str(config['settings']['captcha'].lower()):
        captcha.harvest(queue)
    log('Initializing script..','info')
    '''
    cart.add_to_cart(['zollar','jacket','ice'],'medium')
def hotPotato(names, num):

    q = Queue()

    for name in names:
        q.enqueue(name)

    while q.size() > 1:
        for x in range(num):
            q.enqueue(q.dequeue())
        q.dequeue()

    return q.dequeue()
Пример #22
0
 async def empty(self):
     ''' Clear the queue '''
     if self.shutting_down:
         raise PlayerException("The player already finished.")
     self.__queue = Queue()
Пример #23
0
class MusicPlayer:
    def __init__(self, bot):
        ''' Initialize the MusicPlayer object '''
        self.id = bot.message.server.id
        self.__loop = asyncio.get_event_loop()
        self.chat = bot.message.channel
        self.sender = bot.message.author
        self.channel = bot.message.author.voice_channel
        self.bot = bot
        self.VC = None
        self.Player = None
        self.__queue = Queue()
        self.shutting_down = False
        self.allowed = ["file", "ytdl"]
        self.skipvotes = []
        self.paused = False
        self.oldmsg = None
        self.auto_dc = True

    async def disconnect(self):
        ''' Stops the current music player and disconnects the client '''
        try:
            self.shutting_down = True
            self.__queue = None
            await self.stop()
            if self.VC is not None and self.VC.is_connected():
                await self.VC.disconnect()
            self.VC = None
            del global_vars.music_bots[self.id]
        except:
            logger.PrintException()

    async def connect(self):
        ''' Connects the Client to a Voice channel '''
        if not discord.opus.is_loaded():
            raise PlayerException("Opus is not loaded.")
            # discord.opus.load_opus("libopus-0_x86.dll")
            #if not discord.opus.is_loaded():
            #PlayerException("Could not load Opus dll")
            #return False
        if not self.VC:
            try:
                #logger.printtf("connecting")
                self.VC = await self.bot.client.join_voice_channel(self.channel
                                                                   )
                print("Connected to {}".format(self.channel.name))
                #logger.printtf("connected")
                return True
            except Exception:
                logger.PrintException()
                return False
        else:
            raise ClientException("The MusicPlayer is already connected")

    async def stop(self):
        ''' Stops the current music player '''
        if self.Player is not None:
            if not self.Player.is_done():
                self.Player.stop()
                return True
            self.Player = None
        return False

    async def volume(self, value):
        """Sets the volume of the currently playing song."""

        if self.Player is not None:
            player = self.Player
            player.volume = value / 100
            await config.setConf(self.id, "music_bot_volume", player.volume)
            await self.bot.sendMessage('Set the volume to {:.0%}'.format(
                player.volume))

    async def pause(self):
        ''' Pauses the player '''
        if self.shutting_down:
            raise PlayerException("The player already finished.")
        if self.paused:
            raise PlayerException("The player is already paused.")
        self.Player.pause()
        self.paused = True

    async def resume(self):
        ''' Resumes the player '''
        if self.shutting_down:
            raise PlayerException("The player already finished.")
        if not self.paused:
            raise PlayerException("The player is already playing.")
        self.Player.resume()
        self.paused = False

    async def getqueue(self, position):
        return self.__queue.list[position]

    async def dequeue(self, position):
        return await self.__queue.remove(position)

    async def queuelist(self):
        return await self.__queue.getQueue()

    async def remaining(self):
        ''' Remaining songs in queue '''
        if self.shutting_down:
            raise PlayerException("The player already finished")
        return self.__queue.size()

    async def empty(self):
        ''' Clear the queue '''
        if self.shutting_down:
            raise PlayerException("The player already finished.")
        self.__queue = Queue()

    async def downloadSoundCloud(self, url):
        ''' Tries to get the download URL for soundcloud songs.
        Returns None if it fails '''
        try:
            posturl = "http://soundflush.com/"
            with aiohttp.ClientSession() as session:
                async with session.post(posturl, data={"track_url_field":
                                                       url}) as r:
                    r = re.search('download=\".*\" href=\"(.*)\" class', await
                                  r.text())
                    if r is not None:
                        return r.group(1)
        except:
            logger.PrintException()
        return None

    async def voteSkip(self, user):
        ''' Handles the skipping votes and skips the current songs
        when there were enough votes
        Returns: True/False depending onif the vote was successfull or not'''
        if not user.voice_channel or user.voice_channel.id != self.channel.id:
            await self.bot.sendMessage(
                "You have to be in the bots voice channel to vote for a skip.")
            return False
        members = len(self.channel.voice_members) - 1
        success = False
        if members == 1:
            await self.bot.sendMessage(
                "Skip vote was successful. Skipping song.")
            await self.playNext()
        if members > 0:
            needed = 1
            if members % 2 == 0:
                needed = int((members / 2) + 1)
            else:
                needed = int(math.ceil(members / 2))
        else:
            if self.auto_dc:
                await self.disconnect()
            return success
        # If the user has not voted yet, count the vote and return True
        if not user.id in self.skipvotes:
            self.skipvotes.append(user.id)
            if len(self.skipvotes) < needed:
                await botfunc.autoDelete(
                    10, await self.bot.sendMessage(
                        "{} voted to skip the current song. ({}/{} votes)".
                        format(user.display_name, len(self.skipvotes),
                               needed)))
            success = True
        # We've got enough votes. Skipping.
        if len(self.skipvotes) >= needed:
            await botfunc.autoDelete(
                10, await self.bot.sendMessage(
                    "{} voted to skip the current song.\r\nThe vote was successful. Skipping song."
                    .format(user.display_name)))
            await self.playNext()
            return True
        elif success == False:
            await botfunc.autoDelete(
                10, await self.bot.sendMessage(
                    "You can't vote twice. ({}/{} votes)".format(
                        len(self.skipvotes), needed)))
        return success

    async def playNext(self):
        ''' Play the next song'''

        # Delete the old message
        if self.oldmsg is not None:
            await botfunc.autoDelete(1, self.oldmsg)

        mb_allowed = await config.getConf(self.id, "music_bot")
        if mb_allowed == False:
            self.shutting_down = True
            await self.bot.sendMessage(
                "The music bot has been stopped as it has been disabled by an administrator."
            )
            await self.disconnect()
        if mb_allowed == True:
            if not await self.stop():
                if self.__queue is not None:
                    if not self.__queue.empty():
                        MusicObj = await self.__queue.next()
                        return await self.play(MusicObj)
                    else:
                        if self.auto_dc:
                            await self.disconnect()
                            self.shutting_down = True
        return False

    async def play(self, obj):
        ''' initial play function '''
        try:
            if not self.VC or not self.VC.is_connected:
                raise ClientException("Not connected to a channel")
            if self.Player is not None:
                raise PlayerException(
                    "Could not play. There's another player running.")
            self.skipvotes = []
            obj.type = obj.type.lower()
            if not obj.type in self.allowed:
                raise ArgumentException("Invalid link type.")
            #if obj.type == "ytdl":
            await self.__yt_play(obj)
            #elif obj.type == "file":
            #    await self.__file_play(obj)
            return True
        except:
            logger.PrintException()

    async def add(self, obj):
        ''' Add a song to queue '''
        obj.type = obj.type.lower()
        if obj.type not in self.allowed:
            raise ArgumentException("Invalid link type.")
        if self.shutting_down:
            raise PlayerException("The player already finished.")
        if not self.__queue.full():
            return await self.__queue.add(obj)
        else:
            return False

    async def is_connected(self):
        ''' Is the bot connected? '''
        return (self.VC is not None and self.VC.is_connected())

    async def is_playing(self):
        ''' Is the bot playing? '''
        return (self.Player is not None and not self.Player.is_done())

    async def playing_now(self):
        try:
            if not self.VC or not self.VC.is_connected:
                raise ClientException("Not connected to a channel")
            self.Player.volume = await config.getConf(self.id,
                                                      "music_bot_volume")
            title = self.Player.title
            try:
                if self.Player.duration is not None:
                    secs = self.Player.duration
                    mins = math.floor(secs / 60)
                    secs -= (mins * 60)
                    mins = str(mins).zfill(2)
                    secs = str(secs).zfill(2)
                    # Change this shit so it does only generate the message. ?playing should send it so I can improve the auto deletion
                if self.Player.duration is None:
                    await botfunc.autoDelete(
                        10, await self.bot.sendMessage(
                            "Currently playing `{}` in {}.\r\nQueue: {} left.".
                            format(title, self.channel.name,
                                   self.__queue.size())))
                elif self.Player.is_live:
                    await botfunc.autoDelete(
                        10, await self.bot.sendMessage(
                            "Currently playing `{}` (a livestream) in {}.\r\nQueue: {} left."
                            .format(title, self.channel.name,
                                    self.__queue.size())))
                else:
                    await botfunc.autoDelete(
                        10, await self.bot.sendMessage(
                            "Currently playing `{}` in {}.\r\nDuration: {}:{}\r\nQueue: {} left."
                            .format(title, self.channel.name, mins, secs,
                                    self.__queue.size())))
            except:
                await botfunc.autoDelete(
                    10, await self.bot.sendMessage(
                        "Currently playing {} (a file).".format(title)))
        except:
            logger.PrintException()

    async def __yt_play(self, MusicObj):
        ''' Plays a youtube url '''
        try:
            if not self.VC or not self.VC.is_connected:
                raise ClientException("Not connected to a channel")
            if self.Player is not None:
                raise PlayerException(
                    "Could not play. There's another player running.")
            try:
                opts = {
                    'default_search': 'auto',
                    'quiet': True,
                    'noplaylist': True,
                }
                self.Player = await self.VC.create_ytdl_player(
                    MusicObj.url,
                    after=lambda: self.__loop.create_task(self.playNext()),
                    ytdl_options=opts)
            except DownloadError:
                await botfunc.autoDelete(
                    10, await self.bot.sendMessage(
                        "Could not play `{}`. This video is banned in my country. :sob:"
                        .format(MusicObj.url)))
                await self.stop()
                await self.playNext()
                return False
            except:
                await botfunc.autoDelete(
                    10, await self.bot.sendMessage(
                        "Could not play `{}`. There's something wrong with the link."
                        .format(MusicObj.url)))
                await self.stop()
                await self.playNext()
                return False
            self.Player.start()
            self.Player.volume = await config.getConf(self.id,
                                                      "music_bot_volume")
            if self.Player.title is not None:
                title = self.Player.title
            if self.Player.duration is not None:
                secs = self.Player.duration
                mins = math.floor(secs / 60)
                secs -= (mins * 60)
                mins = str(mins).zfill(2)
                secs = str(secs).zfill(2)
            if self.Player.duration is None:
                #await botfunc.autoDelete(10,await self.bot.sendMessage("Now playing `{}` in {}.\r\n**Requested by:** {}\r\n**Queue:** {} left.".format(title, self.channel.name, MusicObj.user, self.__queue.size())))
                self.oldmsg = await self.bot.sendMessage(
                    "Now playing `{}` in {}.\r\n**Requested by:** {} || **Queue:** {} left."
                    .format(title, self.channel.name, MusicObj.user,
                            self.__queue.size()))
            elif self.Player.is_live:
                #await botfunc.autoDelete(10,await self.bot.sendMessage("Now playing `{}` (a livestream) in {}.\r\n**Requested by:** {}\r\n**Queue:** {} left.".format(title, self.channel.name, MusicObj.user, self.__queue.size())))
                self.oldmsg = await self.bot.sendMessage(
                    "Now playing `{}` (a livestream) in {}.\r\n**Requested by:** {} || **Queue:** {} left."
                    .format(title, self.channel.name, MusicObj.user,
                            self.__queue.size()))
            else:
                #await botfunc.autoDelete(10,await self.bot.sendMessage("Now playing `{}` in {}.\r\n**Requested by:** {}\r\n**Duration:** {}:{}\r\n**Queue:** {} left.".format(title, self.channel.name, MusicObj.user, mins, secs, self.__queue.size())))
                self.oldmsg = await self.bot.sendMessage(
                    "Now playing `{}` in {}.\r\n**Requested by:** {} || **Duration:** {}:{} || **Queue:** {} left."
                    .format(title, self.channel.name, MusicObj.user, mins,
                            secs, self.__queue.size()))
        except:
            logger.PrintException()