#! /usr/bin/env python3
import discord
import asyncio
import logging
import time
import ImportMySecrets

logging.basicConfig(level=logging.INFO)

client = discord.Client()

@client.event
async def on_ready():
   client.accept_invite('https://discord.gg/BNKrdyP')

#Functions
#--------------------------------------------------------------------------------------------------------------------------------------------------------   
async def clear_chat_channel(message):
   counter = 0
   all_messages = client.messages
   target_channel = message.channel
   for message_step in all_messages:
      if message_step.channel == target_channel:
         await client.delete_message(message_step)
         counter += 1
   await client.send_message(message.channel, 'I have removed %s old messages' % counter)

def authorcheck(message):
   return str(message.author) != str(message.content.strip('!purge '))


#Commands 
#--------------------------------------------------------------------------------------------------------------------------------------------------------
@client.event
async def on_message(message):
   print(str(message))
   channel = message.channel
   author = message.author
   
   if message.content.startswith('!test'):
      counter = 0
      tmp = await client.send_message(channel, 'Calculating messages...')
      async for log in client.logs_from(message.channel, limit=100):
        if log.author == message.author:
            counter += 1
            
            
        await client.edit_message(tmp, 'You have {} messages.'.format(counter))
      
   if message.content.startswith('!sleep'):
      All_messages = client.messages
      client.delete_messages(All_messages)
      

   if message.content.startswith('!author'):
      await client.send_message(channel, 'The author of this message is %s' % message.author)
         


   if str(message.author) ==  'FunkyXive#9873':
      await client.send_message(message.channel, 'Morten er SALT', tts=True)

   if message.content.startswith('!clear'):
      await clear_chat_channel(message)

   if message.content == '!purge':
      
      deleted = await client.purge_from(channel, limit=10000, check=authorcheck(message))
      await client.send_message(channel, 'Deleted {} message(s)'.format(len(deleted)))

   if message.content == '!mention':
      storpik = 123
      

#   if message.content.startswith('!clear'):
#      MessageToDelete = await client.get_message(message.channel,'%s' %message.content.strip('!clear '))
 #     await client.delete_message(MessageToDelete)


#Tokens
#-------------------------------------------------------------------------------------------------------------------------------------------------------
client.run(ImportMySecrets.Token1)
