Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import discord
- import asyncio
- import logging
- import time
- import sys
- import datetime
- import os.path
- import json
- from sys import argv
- from datetime import date
- from apiclient.discovery import build
- devKey = 'OOPS'
- def nameTrim(author): #Trims the ID numbers off of names
- nick = (str(author)[0:len(str(author))-5])
- return(nick)
- logging.getLogger('discordDebugger')
- logging.basicConfig(filename='debug logs\discord.log', level=logging.DEBUG)
- logging.debug('Bot launched')
- print('Now logging')
- client = discord.Client()
- @client.event
- async def on_ready():
- print('Logged in as')
- print(client.user.name)
- print(client.user.id)
- print('------')
- logging.debug('Bot connected')
- @client.event
- async def on_message(message):
- cleanMessage = str(message.clean_content)
- server = str(message.server).replace(":","")
- channel = str(message.channel)
- author = message.author
- logFile = ("logs/"
- + server + "/"
- + channel + "/"
- + str(date.today()) + ".txt")
- #Searches for a directory logs/server/channel
- #creates a directory if it can't find one
- if os.path.exists("logs/" + server + "/" + channel) == True:
- with open(logFile, "a") as f:
- f.write(nameTrim(message.author) + ": " + str(cleanMessage) + '\n')
- else:
- os.makedirs("logs/" + server + "/" + channel)
- with open(logFile, "a") as f:
- f.write(nameTrim(message.author) + ": " + str(cleanMessage) + '\n')
- if message.content.startswith('!test'):
- counter = 0
- tmp = await client.send_message(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))
- elif message.content.startswith('!sleep'):
- await asyncio.sleep(5)
- await client.send_message(message.channel, 'Done sleeping')
- elif message.content.startswith('!time'):
- time = date.today()
- print(str(time))
- #searches d20pfsrd when someone types !pfsrd
- elif message.content.startswith('!pfsrd'):
- print('command received')
- searchTerms = str(message.content)
- #splits the content of the message at the space after !test
- trash, searchTerms = searchTerms.split(" ", 1)
- service = build('customsearch', 'v1', developerKey=devKey)
- response = service.cse().list(q=str(searchTerms),
- num='1',
- siteSearch='http://www.d20pfsrd.com/',
- cx='010353485282640597323:i406fguqdfe').execute()
- print(json.dumps(response, sort_keys=True, indent=4))
- #tries to get a URL from the returned information.
- #If it fails, sends a message saying no info was returned.
- try:
- pageUrl = str(response['items'][0]['link'])
- pageBlurb = str(response['items'][0]['htmlSnippet'])
- except:
- await client.send_message(message.channel, 'No results returned.')
- #removes common HTML markers
- pageBlurb = (pageBlurb.replace('<br>', '').replace('</br>', '')
- .replace('<b>', '').replace('</b>', '')
- .replace(' ', '').replace('/n', '').replace('\n', ''))
- try:
- pageTitle = response['items'][0]['pagemap']
- pageTitle = str(pageTitle['webpage'][0]['name'])
- except:
- pageTitle = str(response['items'][0]['title'])
- await client.send_message(message.channel, '**Page found**: '
- + str(pageTitle) + '\n**URL**: '
- + str(pageUrl) + '\n**Snippet**: '
- + pageBlurb)
- #Quote function starts below here
- elif message.content.startswith('!pfquote'):
- server = str(message.server)
- trash, command = str(message.content).split(" ", 1)
- command, user, content = command.split(' ', 2)
- user = str(user.title()) #titlecases usernames
- server = str(server).replace(':','')
- quoteFilePath = str("quotes/" + str(server) + "/" + str(user) + '.log')
- #adding quotes
- if command.startswith('add'):
- if os.path.exists("quotes/" + server) == True:
- with open(quoteFilePath, "a") as f:
- f.write(content + '\n')
- print('wrote to ' + user + ' quotes log')
- else:
- os.makedirs("quotes/" + server)
- with open(quoteFilePath, "a") as f:
- f.write(content + '\n')
- print('created to ' + user + ' quotes log')
- #deleting quotes
- elif command.startswith('del'):
- quoteToDelete = int(content) - 1
- print(quoteToDelete)
- if os.path.exists(quoteFilePath) == False:
- await client.send_message(message.channel,
- 'No quotes exist for that user.')
- elif os.path.exists(quoteFilePath):
- quoteDoc = open(quoteFilePath, 'r')
- quoteList = quoteDoc.readlines()
- quoteDoc.close
- try:
- deletedQuote = quoteList[quoteToDelete]
- del quoteList[quoteToDelete]
- quoteDoc = open(quoteFilePath, 'w')
- quoteDoc.writelines(quoteList)
- quoteDoc.close
- await client.send_message(message.channel,
- 'Deleted quote: ' + deletedQuote)
- except:
- await client.send_message(message.channel,
- 'Quote does not exist.')
- #reading quotes
- elif command.startswith('read'):
- quoteToRead = int(content)
- if os.path.exists(quoteFilePath) == False:
- await client.send_message(message.channel,
- 'No quotes exist for that user.')
- else:
- quoteDoc = open(quoteFilePath, 'r')
- quoteList = quoteDoc.readlines()
- try:
- quote = str(quoteList[quoteToRead - 1])
- quoteDoc.close
- await client.send_message(message.channel,
- '[' + str(quoteToRead) + '/'
- + str(len(quoteList)) + '] '
- + quote)
- except:
- await client.send_message(message.channel,
- 'That user only has '
- + str(len(quoteList)) +
- ' quotes.')
- quoteDoc.close
- client.run('OOPS')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement