Guest User

Untitled

a guest
Jan 12th, 2020
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.77 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import sqlite3
  4. import sys
  5. import click
  6. import datetime
  7.  
  8. import discord
  9.  
  10. client = discord.Client()
  11.  
  12. global_filename = ''
  13. global_guildid = 0
  14.  
  15. @click.command()
  16. @click.option('--bot', '-B', default=False, is_flag=True)
  17. @click.option('--token', '-t', default='')
  18. @click.argument('guildid')
  19. @click.argument('filename')
  20. def main(bot, token, guildid, filename):
  21.     global global_guildid, global_filename
  22.     global_guildid = guildid
  23.     global_filename = filename
  24.     if token == '':
  25.         try:
  26.             client.run(open('token.txt','r').read().split('\n')[0], bot=bot)
  27.         except discord.errors.LoginFailure as e:
  28.             print(e, 'Try adding the `--bot` flag.')
  29.     else:
  30.         try:
  31.             client.run(token, bot=bot)
  32.         except discord.errors.LoginFailure as e:
  33.             print(e, 'Try adding the `--bot` flag.')
  34.  
  35. @client.event
  36. async def on_ready():
  37.     print("Backup bot logged in.")
  38.     await make_logs()
  39.     await client.logout()
  40.    
  41. async def make_logs():
  42.     database = None
  43.     def scrub(s):
  44.         while "-" in s:
  45.             s = s.replace("-", "")
  46.         return s
  47.     def check_table_exists(tablename):
  48.         dbcur = database.cursor()
  49.         dbcur.execute("""
  50.            SELECT name FROM sqlite_master WHERE type='table' AND name='{0}';
  51.            """.format(str(tablename).replace('\'', '\'\'')))
  52.         if dbcur.fetchone():
  53.             dbcur.close()
  54.             return True
  55.  
  56.         dbcur.close()
  57.         return False
  58.    
  59.     guild = client.get_guild(int(global_guildid))
  60.     database = sqlite3.connect("{}.sqlite".format(global_filename))
  61.    
  62.     cursor = database.cursor()
  63.     if check_table_exists('channels'):
  64.         cursor.execute("""DROP TABLE channels""")
  65.     cursor.execute("""CREATE TABLE channels(cid INTEGER, position INTEGER, name TEXT, topic TEXT, type TEXT)""")
  66.     cursor.close()
  67.     database.commit()
  68.     for channel in guild.channels:
  69.         if isinstance(channel, discord.TextChannel):
  70.             cursor = database.cursor()
  71.             cursor.execute(
  72.                 """INSERT INTO channels(cid, position, name, topic, type) VALUES (?, ?, ?, ?, ?)""",
  73.                 (channel.id, channel.position, channel.name, str(channel.topic), 'discord.TextChannel')
  74.             )
  75.             cursor.close()
  76.             database.commit()
  77.             if channel.permissions_for(guild.get_member(client.user.id)).read_message_history:
  78.                 sys.stdout.write("Logging {0}: Counting".format(channel.name))
  79.                 sys.stdout.flush()
  80.                 cursor = database.cursor()
  81.                 after = datetime.datetime(2015,3,1)
  82.                 if check_table_exists(channel.id):
  83.                     cursor.execute("""SELECT timestamp FROM `{0}` ORDER BY timestamp DESC LIMIT 1""".format(channel.id))
  84.                     try:
  85.                         after = datetime.datetime.strptime(cursor.fetchone()[0], "%Y-%m-%d %H:%M:%S.%f")
  86.                     except TypeError:
  87.                         pass
  88.                 else:
  89.                     cursor.execute("""CREATE TABLE `{0}`(uid INTEGER, mid INTEGER, message TEXT, files TEXT, timestamp TEXT)""".format(channel.id))
  90.                 database.commit()
  91.                 count = 0
  92.                 msg_c = 0
  93.                 async for message in channel.history(limit=None,after=after):
  94.                     msg_c += 1
  95.                 print("\rLogging {0}: 0/{1}         ".format(channel.name, msg_c), end="")
  96.                 async for message in channel.history(limit=None,after=after):
  97.                     at = ",".join([i.url for i in message.attachments])
  98.                     cursor.execute("""
  99.                        INSERT INTO `{0}`(uid, mid, message, files, timestamp)
  100.                        VALUES (?, ?, ?, ?, ?)""".format(channel.id), (message.author.id, message.id, message.content, at, message.created_at))
  101.                     count += 1
  102.                     if count % 200 == 0:
  103.                         database.commit()
  104.                         print("\rLogging {0}: {1}/{2}".format(channel.name, count, msg_c), end="")
  105.                 database.commit()
  106.                 print("\rLogging {0}: [DONE]            ".format(channel.name))
  107.         elif isinstance(channel, discord.VoiceChannel):
  108.             cursor = database.cursor()
  109.             cursor.execute(
  110.                 """INSERT INTO channels(cid, position, name, topic, type) VALUES (?, ?, ?, ?, ?)""",
  111.                 (channel.id, channel.position, channel.name, '', 'discord.VoiceChannel')
  112.             )
  113.             cursor.close()
  114.             database.commit()
  115.     print("LOGS FINISHED")
  116.  
  117. if __name__ == '__main__':
  118.     #bot=False may have to be changed if you are using a bot
  119.     client.run(open('token.txt','r').read().split('\n')[0], bot=True)
  120.     main()
Advertisement
Add Comment
Please, Sign In to add comment