repl.it
@pyelias/

replbot

Python

really old discord bot from repl.it

fork
loading
Files
  • main.py
  • test
  • hangman.py
  • py_runner.py
  • words
  • Packager files
  • poetry.lock
  • pyproject.toml
  • requirements.txt
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# wow this code is really bad

import discord
from flask import Flask
import lupa
import requests
import time
import asyncio
import sys
import os
import io
import subprocess
import importlib
import fileinput
import shutil
import threading
import random
from collections import defaultdict

real_sys_exit = sys.exit

def new_sys_exit(*args, **kwargs):
  print("not allowed")
sys.exit = new_sys_exit
sys._exit = new_sys_exit

os.system = os.remove = os.open = os._exit = os.rmdir = os.unlink = os.mkdir = os.rename = os.open = os.fork = new_sys_exit
io.open = new_sys_exit
fileinput.input = new_sys_exit
importlib.reload = new_sys_exit
subprocess.Popen = subprocess.run = subprocess.call = new_sys_exit
shutil.rmtree = new_sys_exit

sys.modules["__main__"] = "nope"
sys.modules["main"] = "nope"
sys.modules["hangman"] = "nope"
sys.modules["pathlib"] = "nope"

def discord_thread():
  import hangman
  
  bot_id = random.randint(0, 1000000)
  
  BOT_4BIT_ID = 386333909362933772
  bot_4bit = None

  ADMINS = {
    242780754621366272, # pyelias
    440231799533338634, # kingofcode
  }

  asyncio.set_event_loop(asyncio.new_event_loop())
  client = discord.Client()
  
  @client.event
  async def on_ready():
    print("bot ok and going")

    #nonlocal bot_4bit
    #bot_4bit = await client.get_user_info(BOT_4BIT_ID)
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('copy paste this in your browser to authorize bot https://discordapp.com/oauth2/authorize?client_id={}&scope=bot&permissions=0'.format(os.environ['CLIENTID']))
    print('------')
    # await client.edit_profile(username="replbot")
  
  CMD_DESC = {
    "cmds": "List all commands",
    "getid": "Get the bot id",
    "killid": "Kill the bot with the given id",
    "saveid": "Kill bots without the given id",
    "py": "Run python code",
    "lua": "Run lua code",
    "remind": "set a reminder",
  }
  
  PY_EASTER_EGGS = {
    "import antigravity": "https://xkcd.com/353/",
    "import soul": "https://xkcd.com/413/",
    "import skynet": "https://xkcd.com/521/",
    "import this":  "Beautiful is better than ugly."
                    "Explicit is better than implicit."
                    "Simple is better than complex."
                    "Complex is better than complicated."
                    "Flat is better than nested."
                    "Sparse is better than dense."
                    "Readability counts."
                    "Special cases aren't special enough to break the rules."
                    "Although practicality beats purity."
                    "Errors should never pass silently."
                    "Unless explicitly silenced."
                    "In the face of ambiguity, refuse the temptation to guess."
                    "There should be one-- and preferably only one --obvious way to do it."
                    "Although that way may not be obvious at first unless you're Dutch."
                    "Now is better than never."
                    "Although never is often better than *right* now."
                    "If the implementation is hard to explain, it's a bad idea."
                    "If the implementation is easy to explain, it may be a good idea."
                    "Namespaces are one honking great idea -- let's do more of those!"
  }

  async def get_langs(_, __, message):
    await message.channel.send("\n".join(f"{cmd} - {desc}" for cmd, desc in CMD_DESC.items()))
  
  async def get_id(id_, __, message):
    if int(id_) in ADMINS:
      await message.channel.send(str(bot_id))
  
  async def kill_id(id_, to_kill, ___):
    if int(id_) in ADMINS and to_kill == str(bot_id):
      exit()
  
  async def save_id(id_, to_kill, ___):
    if int(id_) in ADMINS and to_kill != str(bot_id):
      exit()
  
  async def say(_, to_say, message):
    #if to_say.startswith("%") or to_say.startswith("-"):
    #  await message.channel.send(f"no bad {message.author.name}")
    #  return
    await message.channel.send(to_say)
  
  async def hangman_get_resp(letter, message):
    await message.channel.send(letter)
    resp = await client.wait_for_message(author=bot_4bit)
    resp = resp.content.split("\n")[0].replace(" ", "").replace("\\", "")
    print(resp)
    return tuple(ind for ind, char in enumerate(resp) if char == letter)
  
  async def play_hangman(_, __, message):
    await message.channel.send("/hangman")
    await client.wait_for_message(author=bot_4bit) # absorb game init
    print("recdv")
    await message.channel.send("whatevs dude dont care")
    start = await client.wait_for_message(author=bot_4bit)
    print("recdv")
    length = len(start.content.split("\n")[0].replace(" ", "").replace("\\", ""))
    game = hangman.play(length)
    letter = next(game)
    while True:
      try:
        letter = game.send(await hangman_get_resp(letter, message))
      except StopIteration:
        break
  
  async def run_python(id_, code, message):
    if code in PY_EASTER_EGGS:
      await message.channel.send(PY_EASTER_EGGS[code])
      return
    await message.channel.send("this command is bad dont use it")
    return

    print(f"Running from {id_}")
    glob = run_python.envs.get(id_, {"__builtins__": run_python.bltins})
    sys.stdout = sys.stderr = stream = io.StringIO()
    def runner():
      exec(code, glob)
    thread = threading.Thread(None, runner)
    thread.start()
    thread.join(timeout=5)
    time.sleep(1)
    res = stream.getvalue()
    if thread.is_alive():
      res += "<timed out>"
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    run_python.envs[id_] = glob
    if not res:
      res = "<no output>"
    if len(res) > 1000: 
      res = res[:(1000-22)] + "<output limit reached>"
    if res.count("\n") > 15:
      res = res.split("\n")
      res = "\n".join(res[:15]) + "\n<output limit reached>"
    await message.channel.send(f"```\n{res}```")
  
  run_python.envs = {}
  run_python.bltins = __builtins__.__dict__.copy()
  run_python.bltins["open"] = lambda *args, **kwargs: print("open() not allowed")
  
  def safe_lua_runtime():
    env = lupa.LuaRuntime()
    del env.globals().python
    env.globals().io.open = env.eval("function(...) print('not allowed') end")
    return env
  
  async def run_lua(id_, code, message):
    await message.channel.send("this command is bad dont use it")
    return

    print(f"Running from {id_}")
    glob = run_lua.envs.get(id_, safe_lua_runtime()) # i know this creates one each time
    output = []
    glob.globals().io.write = lambda s: output.append(str(s))
    glob.globals().print = lambda s: output.append(str(s) + "\n")
    def runner():
      try:
        glob.execute(code)
      except lupa.LuaError as e:
        output.append(f"{type(e).__name__}({e})")
    thread = threading.Thread(None, runner)
    thread.start()
    thread.join(timeout=5)
    res = "".join(output)
    run_lua.envs[id_] = glob
    if not res:
      res = "<no output, code may have timed out>"
    if len(res) > 1000: 
      res = res[:(1000-22)] + "<output limit reached>"
    if res.count("\n") > 15:
      res = res.split("\n")
      res = "\n".join(res[:15]) + "\n<output limit reached>"
    print(f"```\n{res}```")
    await message.channel.send(f"```\n{res}```")
  
  run_lua.envs = {}

  async def remind(id_, code, message):
    time, what = code.split(" ", 1)
    await message.channel.send(f"Ok, reminding you about '{what}' in {time} minutes")
    await asyncio.sleep(60 * float(time))
    await message.channel.send(f"Hey, <@{id_}>, remember {what}?")
  
  async def order(_, what, message):
    if what == "pizza":
      await message.channel.send(f"-pizza")
    elif what == "a microwaved microwaved toaster":
      await message.channel.send(f"-microwave")
  
  CMDS = {
    "cmds": get_langs,
    "getid": get_id,
    "killid": kill_id,
    "saveid": save_id,
    "say": say,
    "hangman": play_hangman,
    "py": run_python,
    "lua": run_lua,
    "remind": remind,
    "order": order,
  }
  
  @client.event
  async def on_message(message):
    if message.author.id == client.user.id:
      return
    try:
      if message.content.startswith("!replbot") or message.content.startswith("replbot,"):
        #if message.author.id == '220663962616856576':
        #  await message.channel.send("zwack stahp")
        #  return
        if message.author.bot and 0:
          await message.channel.send("no ur a bot")
          return
        args = message.content.split(maxsplit=2)
        if len(args) == 2:
          cmd = args[1]
          code = ""
        elif len(args) == 3:
          cmd = args[1]
          code = args[2].strip()
        else:
          await message.channel.send("too few arguments")
          return
        
        cmd = cmd.strip("`")
  
        if cmd not in CMDS:
          await message.channel.send("unknown command")
          return
        
        while code.startswith("`"):
          code = code[1:]
        while code.endswith("`"):
          code = code[:-1]
        await CMDS[cmd](message.author.id, code, message)
    except RuntimeError as e:
      await message.channel.send(f"unexpected error: {type(e).__name__}({e})")
      return
  
  print("bot go")
  client.run(os.environ['TOKEN'])

def flask_thread():
  hits = 0
  app = Flask(__name__)
  
  @app.route("/")
  def main():
    nonlocal hits
    hits += 1
    return f"{hits} current page hits"
  
  app.run(host="0.0.0.0")
  print("running")

def request_thread():
  URL = "http://discord-bot--replitcode.repl.co"
  while True:
    print("request")
    requests.get(URL)
    time.sleep(30)

#threading.Thread(None, discord_thread).start() # bot component
threading.Thread(None, flask_thread).start()   # open port to allow requests
threading.Thread(None, request_thread).start() # keep repl alive
discord_thread()
Fetching token
?