Browse Source

initial commit :3

master
Agatha 6 months ago
commit
192aa395a5
Signed by: sorceress <agatharose@wantscuddl.es> GPG Key ID: 2DB18BA2E0A80BC3
2 changed files with 183 additions and 0 deletions
  1. +7
    -0
      .gitignore
  2. +176
    -0
      main.py

+ 7
- 0
.gitignore View File

@@ -0,0 +1,7 @@
venv/
removed-data/
data/
models/
checkpoint/
token
.vscode

+ 176
- 0
main.py View File

@@ -0,0 +1,176 @@
import discord
from discord.ext import commands
from discord import Webhook, RequestsWebhookAdapter
import os.path
import time
import json
import random
from markovchain.text import MarkovText, ReplyMode

intents = discord.Intents.default()
intents.typing = False
intents.presences = False
intents.members = True

# yoinked from nyandroid :3

try:
with open("token") as f:
TOKEN = f.read().rstrip()
except FileNotFoundError:
print(
"make sure you run this from the root dir, and that you have"
" the token file present")
exit(1)


# TODO: replace with actual id later
SOURCE_SERVER_ID = 689023661864386561
TARGET_SERVER_ID = 767451816459108372
TARGET_CHANNEL_ID = 767994630615728138


class Kommune2(commands.Bot):
async def on_ready(self):
print('Logged in as {0}!'.format(self.user))


client = Kommune2(command_prefix='%', intents=intents)


@client.event
async def on_member_join(member):
observer_role = member.get_guild().get_role(767452466614108181)
await member.add_roles(observer_role)


@client.event
async def on_message(message):
if message.author == client.user:
return
else:
await client.process_commands(message)

if message.content.startswith('%'):
return

if message.guild.id == TARGET_SERVER_ID:
# pick a random user
filename = random.choice(os.listdir("data/"))

# load user data and messages
f = open(f'data/{filename}')
data = json.load(f)
messages = '\n'.join(data['messages'])

# create webhook or find existing one
webhooks = await message.channel.webhooks()
if not len(webhooks):
webhook = await message.channel.create_webhook(
name='Text Generation Webhook')
else:
webhook = Webhook.from_url(
url=webhooks[0].url,
adapter=RequestsWebhookAdapter())

if message.channel.id == TARGET_CHANNEL_ID:
markov = MarkovText()
markov.data(messages)

# reply to last message
if random.random() < 0.3:
out = markov(max_length=300,
reply_to=message.content,
reply_mode=ReplyMode.END)
out = out[len(message.content):]
# initiate a new conversation
else:
out = markov(max_length=300,
reply_mode=ReplyMode.END)

# prevent empty message error
if not len(out):
out = '[ could not generate a message, sowwy ]'

# remove pings
out = out.replace('@', '@\u200b')

webhook.send(
out,
username=f"{data['displayname']}bot",
avatar_url=data['avatar'])

if message.content == '[ could not generate a message, sowwy ]':
await message.delete()

if message.guild.id == TARGET_SERVER_ID:
time.sleep(random.randint(5, 20))


@client.command()
async def populate(ctx, limit: int = 500):
print(
"Creating json files...\n"
f"msg limit: {limit}"
)

# get the source guild to take messages from
guild = discord.utils.find(
lambda g: g.id == SOURCE_SERVER_ID, client.guilds)

print(f'target server: {guild.name} [id: {guild.id}]\n')

for member in guild.members:
# initialize the json structure
data = {}
data['displayname'] = member.display_name
data['avatar'] = str(member.avatar_url)
data['messages'] = []

# get all messages
for channel in guild.text_channels:
async for msg in channel.history(limit=limit):
if msg.author == member:
data['messages'].append(msg.content)
print(
f"\t-> saved message {msg.id} by {msg.author.display_name}")

# check if file exists
filename = f'data/{member.id}.json'
if os.path.isfile(filename):
os.remove(filename)
with open(filename, 'w') as out:
json.dump(data, out, indent=4)
else:
# otherwise, create a new file and dump data there
with open(filename, 'w') as out:
json.dump(data, out, indent=4)

# clean up empty files
with open(filename) as f:
filedata = json.load(f)
if not filedata.get('messages'):
os.remove(filename)

print("\n\nPOPULATION DONE\n\n")


@client.command()
async def generate(ctx, text_in: str = 'uwu'):
filename = f'data/{random.choice(os.listdir("data/"))}'
if os.path.isfile(filename):
with open(filename) as f:
data = json.load(f)
messages = '\n'.join(data['messages'])

markov = MarkovText()
markov.data(messages)

print("not influenced: [[" + markov() + ']]\n')
print(f"influenced by input \"{text_in}\": [[" +
markov(max_length=16,
reply_to=text_in,
reply_mode=ReplyMode.END) + "]]\n")


client.run(TOKEN)

Loading…
Cancel
Save