Advertisement
Snowshoe2

ReferenceBot

Aug 24th, 2016
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.12 KB | None | 0 0
  1. import discord
  2. import asyncio
  3. import logging
  4. import time
  5. import sys
  6. import datetime
  7. import os.path
  8. import json
  9. from sys import argv
  10. from datetime import date
  11. from apiclient.discovery import build
  12.  
  13. devKey = 'OOPS'
  14.  
  15.  
  16. def nameTrim(author): #Trims the ID numbers off of names
  17.     nick = (str(author)[0:len(str(author))-5])
  18.     return(nick)
  19.  
  20. logging.getLogger('discordDebugger')
  21. logging.basicConfig(filename='debug logs\discord.log', level=logging.DEBUG)
  22. logging.debug('Bot launched')
  23. print('Now logging')
  24.  
  25.  
  26. client = discord.Client()
  27. @client.event
  28. async def on_ready():
  29.     print('Logged in as')
  30.     print(client.user.name)
  31.     print(client.user.id)
  32.     print('------')
  33.     logging.debug('Bot connected')
  34.  
  35. @client.event
  36. async def on_message(message):
  37.     cleanMessage = str(message.clean_content)
  38.     server = str(message.server).replace(":","")
  39.     channel = str(message.channel)
  40.     author = message.author
  41.     logFile = ("logs/"
  42.                + server + "/"
  43.                + channel + "/"
  44.                + str(date.today()) + ".txt")
  45.     #Searches for a directory logs/server/channel
  46.     #creates a directory if it can't find one
  47.     if os.path.exists("logs/" + server + "/" + channel) == True:
  48.         with open(logFile, "a") as f:
  49.             f.write(nameTrim(message.author) + ": " + str(cleanMessage) + '\n')
  50.     else:
  51.         os.makedirs("logs/" + server + "/" + channel)
  52.         with open(logFile, "a") as f:
  53.             f.write(nameTrim(message.author) + ": " + str(cleanMessage) + '\n')
  54.        
  55.     if message.content.startswith('!test'):
  56.         counter = 0
  57.         tmp = await client.send_message(message.channel,
  58.                                         'Calculating messages...')
  59.         async for log in client.logs_from(message.channel, limit=100):
  60.             if log.author == message.author:
  61.                 counter += 1
  62.  
  63.         await client.edit_message(tmp, 'You have {} messages.'.format(counter))
  64.     elif message.content.startswith('!sleep'):
  65.         await asyncio.sleep(5)
  66.         await client.send_message(message.channel, 'Done sleeping')
  67.  
  68.     elif message.content.startswith('!time'):
  69.         time = date.today()
  70.         print(str(time))
  71.  
  72.     #searches d20pfsrd when someone types !pfsrd
  73.     elif message.content.startswith('!pfsrd'):
  74.         print('command received')
  75.         searchTerms = str(message.content)
  76.         #splits the content of the message at the space after !test
  77.         trash, searchTerms = searchTerms.split(" ", 1)
  78.         service = build('customsearch', 'v1', developerKey=devKey)
  79.         response = service.cse().list(q=str(searchTerms),
  80.                                       num='1',
  81.                                       siteSearch='http://www.d20pfsrd.com/',
  82.                                       cx='010353485282640597323:i406fguqdfe').execute()
  83.         print(json.dumps(response, sort_keys=True, indent=4))
  84.         #tries to get a URL from the returned information.
  85.         #If it fails, sends a message saying no info was returned.
  86.         try:
  87.             pageUrl = str(response['items'][0]['link'])
  88.             pageBlurb = str(response['items'][0]['htmlSnippet'])
  89.         except:
  90.             await client.send_message(message.channel, 'No results returned.')
  91.         #removes common HTML markers    
  92.         pageBlurb = (pageBlurb.replace('<br>', '').replace('</br>', '')
  93.                     .replace('<b>', '').replace('</b>', '')
  94.                     .replace('&nbsp;', '').replace('/n', '').replace('\n', ''))
  95.         try:
  96.             pageTitle = response['items'][0]['pagemap']
  97.             pageTitle = str(pageTitle['webpage'][0]['name'])
  98.  
  99.         except:
  100.             pageTitle = str(response['items'][0]['title'])
  101.  
  102.         await client.send_message(message.channel, '**Page found**: '
  103.                                   + str(pageTitle) + '\n**URL**: '
  104.                                   + str(pageUrl) + '\n**Snippet**: '
  105.                                   + pageBlurb)
  106.  
  107. #Quote function starts below here
  108.  
  109.     elif message.content.startswith('!pfquote'):
  110.         server = str(message.server)
  111.         trash, command = str(message.content).split(" ", 1)
  112.         command, user, content = command.split(' ', 2)
  113.         user = str(user.title()) #titlecases usernames
  114.         server = str(server).replace(':','')
  115.         quoteFilePath = str("quotes/" + str(server) + "/" + str(user) + '.log')
  116.         #adding quotes
  117.         if command.startswith('add'):
  118.             if os.path.exists("quotes/" + server) == True:
  119.                 with open(quoteFilePath, "a") as f:
  120.                     f.write(content + '\n')
  121.                 print('wrote to ' + user + ' quotes log')
  122.             else:
  123.                 os.makedirs("quotes/" + server)
  124.                 with open(quoteFilePath, "a") as f:
  125.                     f.write(content + '\n')
  126.                 print('created to ' + user + ' quotes log')
  127.         #deleting quotes        
  128.         elif command.startswith('del'):
  129.             quoteToDelete = int(content) - 1
  130.             print(quoteToDelete)
  131.             if os.path.exists(quoteFilePath) == False:
  132.                 await client.send_message(message.channel,
  133.                                           'No quotes exist for that user.')
  134.             elif os.path.exists(quoteFilePath):
  135.                 quoteDoc = open(quoteFilePath, 'r')
  136.                 quoteList = quoteDoc.readlines()
  137.                 quoteDoc.close
  138.                 try:
  139.                     deletedQuote = quoteList[quoteToDelete]
  140.                     del quoteList[quoteToDelete]
  141.                     quoteDoc = open(quoteFilePath, 'w')
  142.                     quoteDoc.writelines(quoteList)
  143.                     quoteDoc.close
  144.                     await client.send_message(message.channel,
  145.                                               'Deleted quote: ' + deletedQuote)
  146.                 except:
  147.                     await client.send_message(message.channel,
  148.                                               'Quote does not exist.')
  149.            
  150.         #reading quotes
  151.         elif command.startswith('read'):
  152.             quoteToRead = int(content)
  153.             if os.path.exists(quoteFilePath) == False:
  154.                 await client.send_message(message.channel,
  155.                                           'No quotes exist for that user.')
  156.             else:
  157.                 quoteDoc = open(quoteFilePath, 'r')
  158.                 quoteList = quoteDoc.readlines()
  159.                 try:
  160.                     quote = str(quoteList[quoteToRead - 1])
  161.                     quoteDoc.close
  162.                     await client.send_message(message.channel,
  163.                                               '[' + str(quoteToRead) + '/'
  164.                                               + str(len(quoteList)) + '] '
  165.                                               + quote)
  166.                 except:
  167.                     await client.send_message(message.channel,
  168.                                             'That user only has '
  169.                                               + str(len(quoteList)) +
  170.                                               ' quotes.')
  171.                     quoteDoc.close
  172.                                
  173.  
  174. client.run('OOPS')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement