[PYTHON] When I made a Discord Bot, my classmates destroyed my computer

The title is amazing, but the content is the story of making a Discord Bot normally.

The sentence of this problem

if not message.author.id == client.user.id:
        ms = message.content  #Image command judgment
        ms = ms[:6]  #Judgment is made by cutting out only the first six characters of all messages
        if ms == "!image":
            overlap = 0
            ms = (message.content[7:])  #ms is only a message(!Shave the image)
            filepath1 = "./downloads"  #To join later
            files1 = os.listdir(filepath1)  #I put all directory names in files
            leng = len(files1)  #Determine the length of the array of files
            i = 0

            for i in range(leng):
                if ms == files1[i]:
                    overlap = 1
                    break
                i += 1

    if overlap == 1:
        print("I used an image that is local without scraping")  #For confirmation
        filepath = './downloads/' + ms + "/"  #Where the file is
        files = os.listdir(filepath)  #I put the name of the contents of the file in a variable
        files = files[0]  #Since it enters in an array, it is the first of them
        path1 = filepath + files  #Generate the final path of the image
        await message.channel.send(file=discord.File(path1))  #Send image

    else:
        print("I scraped because I could not see the image locally")  #For confirmation
        response = google_images_download.googleimagesdownload()  #Google image scraping library
        arguments = {"keywords": ms, "limit":1,"print_urls":True}#Search word and number of sheets specified
        paths = response.download(arguments)  #Scraping,
        print(paths)  #Output log
        ms = (message.content[7:])
        filepath = './downloads/' + ms + "/"  #Generate a path of which file in the file
        files = os.listdir(filepath)  #I put the name of the contents of the file in a variable
        files = files[0]  #Since it enters in an array, it is the first of them
        path1 = filepath + files  #Generate the final path of the image
        print(path1)
        await message.channel.send(file=discord.File(path1))  #Send image

Since the characters sent by the user are put in the path, the user can specify where to save them! !! !! My classmates discovered it and the contents of my computer were messed up. Useless files were created in various places, the worst thing is that "..." ← A file with this name was created. This file that I don't understand seems to be a bug in Windows. "..." Opening this will open the previous directory. So if you have this file in Desktop, when you open it, you will find Desktop inside. Moreover, the file cannot be deleted normally, even with `rm ...` in the command prompt of Windows ... So I erased it with Cygwin. It was hard to erase. ___ You should definitely stop running such services on your main PC ___ Will be ** to the bad guys

file organization

DiscordBot/  ├ discordbot.py  └ img/   ├ hare.png   ├ harekumorri.png   ├ jikoku.png   ├ kumori.png  └ downloads

Execution environment

discord.py


import datetime
import io
import os
import time

import aiohttp
import discord
import requests
import schedule
from discord.ext import commands
from google_images_download import google_images_download
from PIL import Image, ImageDraw, ImageFont, ImageTk

#Replace with your bot's access token
TOKEN = "My token"

#Generate the objects needed for the connection
client = discord.Client()

#Processing that operates at startup
@client.event
async def on_ready():
    #When started, a login notification will be displayed in the terminal
    print('You are now logged')

@client.event
async def on_message(message):

   #Ignore if the message sender is a bot
    if message.author.bot:
        return
    # 「/Processing that returns "Nyan" when you say "neko"
    if message.content == '/neko':
        await message.channel.send('Nyan')
    if message.content == '/konn':
        t_now = datetime.datetime.now().time()
        t_now = str(t_now)
        t_now = t_now[:2]
        print(t_now)
        t_now = int(t_now)
        print(type(t_now))
        print(t_now)

        if 5 <= t_now < 12:
            await message.channel.send('Good morning')


        elif 12 <= t_now < 18:
            await message.channel.send('Hello')

        elif 18 <= t_now < 24:
            await message.channel.send('Good evening')

        elif 0 <= t_now < 5:
            await message.channel.send('It's late at night! Let's sleep!')

    if message.content == 'Tomorrow's weather':
        url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=130010'
        api_data = requests.get(url).json()
        weather = api_data['forecasts'][1]
        result = weather["telop"]
        await message.channel.send(api_data['title'] + '\n' 'Tomorrow's weather' + result)
        if result == "Sunny":
            await message.channel.send(file=discord.File('./img/hare.png'))
        elif result == "Cloudy":
            await message.channel.send(file=discord.File("./img/kumori.png "))
        else:
            await message.channel.send(file=discord.File("./img/harekumori.jpg "))

    if message.content == 'today's weather':
        url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=130010'
        api_data = requests.get(url).json()
        weather = api_data['forecasts'][0]
        result = weather["telop"]
        await message.channel.send(api_data['title'] + '\n' 'How is the weather today' + result)
        if result == "Sunny":
            await message.channel.send(file=discord.File('.\\img\\hare.png'))
        elif result == "Cloudy":
            await message.channel.send(file=discord.File(".\\img\\kumori.jpg "))
        else:
            await message.channel.send(file=discord.File(".\\img\\harekumori.png "))

    if message.content == 'Top secret command>>Poop<<':
        await message.channel.send('https://i.gzn.jp/img/2017/10/19/golden-unko-jewelry/00_m.jpg')

   # if message.content == 'Nah':
   #     ar1t = (
   #           '```(≧Д≦)' + '\n' +
 #'....................... ,,, z = ~''+' 彡 ,,' +'\ n'+
 #'...................., i'............ "':';:; tsu ;,' +' \ n'+
 #'................' ‘’ ‘’ ‘Mi’, ..............“ ’,`, ’+’ \ n'+
 #'.........., / ....... `, Gumi .....:;:,' + '\ n'+
 #'......... / .......... = ヾ, ヾ =;, z, .......... ‥; +'\ n'+
 #'....... / ........, r,'... /.' `ヽ. ヽ. ヽ` ........., 彡: Mi'+' \ n'+
 #'..... / ......,'-, .` ヽ ..................... ミ; :: 彡;:' + '\ n'+
 #'...,' ....., Shi'` ヽ ʻi`! ................ ,, 彡; :: Shi: 彡'+' \ n '+
 #'..; ....., (' ̄` ヽ /'.............. Shi: Shi;: Mi :: Shi "'+'\ n'+
 #'´ :::::. ヾ .....  ̄´ ..............'`, simi'+'\ n'+
 #':::::::::::::. `: ヽ, .................:;'_, So'" +'\ n'+
   #           'Nahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh```')
   #     await message.channel.send(ar1t)

    if client.user in message.mentions:
        reply = f'{message.author.mention}called?'
        await message.channel.send(reply)

    if message.content == 'Times of Day':

        #Loading images
        img = Image.open("./img/jikoku.png ")
        #Create draw instance
        draw = ImageDraw.Draw(img)
        #Font settings(Font file path and font size)
        font = ImageFont.truetype("./fonts/BIZ-UDGothicB.ttc", 200)
        #Write letters

        dt = datetime.datetime.now()
        dt = str(dt)
        dt = (dt[11:-10])
        print(dt)

        draw.text((310, 250), dt, fill=(0, 0, 0), font=font)

        img.save("./img/jikoku1.png ")

        print("ok")

        await message.channel.send(file=discord.File(".\\img\\jikoku1.png "))

    if message.content == 'Tax increase':
        await message.channel.send('https://pbs.twimg.com/media/EFUS5YlU0AIAwok?format=jpg&name=small')

    if message.content == 'kusa':
        await message.channel.send(file=discord.File('.\\img\\kusa.jpg'))

    if message.content == 'Cute child':
        await message.channel.send(file=discord.File('.\\img\\1.jpg'))

    if message.content == "How nice":
        await message.channel.send(file=discord.File('.\\img\\good.png'))


    if not message.author.id == client.user.id:
        ms = message.content  #Image command judgment
        ms = ms[:6]  #Judgment is made by cutting out only the first six characters of all messages
        if ms == "!image":
            overlap = 0
            ms = (message.content[7:])  #ms is only a message(!Shave the image)
            filepath1 = "./downloads"  #To join later
            files1 = os.listdir(filepath1)  #I put all directory names in files
            leng = len(files1)  #Determine the length of the array of files
            i = 0

            for i in range(leng):
                if ms == files1[i]:
                    overlap = 1
                    break
                i += 1

    if overlap == 1:
        print("I used an image that is local without scraping")  #For confirmation
        filepath = './downloads/' + ms + "/"  #Where the file is
        files = os.listdir(filepath)  #I put the name of the contents of the file in a variable
        files = files[0]  #Since it enters in an array, it is the first of them
        path1 = filepath + files  #Generate the final path of the image
        await message.channel.send(file=discord.File(path1))  #Send image

    else:
        print("I scraped because I could not see the image locally")  #For confirmation
        response = google_images_download.googleimagesdownload()  #Google image scraping library
        arguments = {"keywords": ms, "limit":1,"print_urls":True}#Search word and number of sheets specified
        paths = response.download(arguments)  #Scraping,
        print(paths)  #Output log
        ms = (message.content[7:])
        filepath = './downloads/' + ms + "/"  #Generate a path of which file in the file
        files = os.listdir(filepath)  #I put the name of the contents of the file in a variable
        files = files[0]  #Since it enters in an array, it is the first of them
        path1 = filepath + files  #Generate the final path of the image
        print(path1)
        await message.channel.send(file=discord.File(path1))  #Send image

    if message.content == "History":
        files1 = os.listdir("./downloads")
        await message.chnanel.send(files1)
        print("History command")

    if message.content == "!helpC":
        await message.channel.send("nothing special")
        
#Launching a bot and connecting to a Discord server
client.run(TOKEN)

Recommended Posts

When I made a Discord Bot, my classmates destroyed my computer
I made a discord bot
I made a Discord bot in Python that translates when it reacts
I made a wikipedia gacha bot
I made a Discord chat reading bot by imitating the appearance
I made a stamp substitute bot with line
I made my dog "Monaka Bot" with LineBot
I made a LINE Bot with Serverless Framework!
I made a Mattermost bot with Python (+ Flask)
〇✕ I made a game
I made my goimports
[AWS] I made a reminder BOT with LINE WORKS
I made a Twitter BOT with GAE (python) (with a reference)
I made a household account book bot with LINE Bot
I made a LINE BOT with Python and Heroku
A story that stumbled when I made a chatbot with Transformer
Let's make a Discord Bot.
I made a LINE BOT that returns parrots with Go
I made my own language. (1)
I made a python text
I made my own language (2)
I made a script to say hello at my Koshien
[AWS] I made a reminder BOT with LINE WORKS (implementation)
[Python] I made a Line bot that randomly asks English words.
I made a Twitter bot that mutters Pokemon caught by #PokemonGO
I made a Twitter Bot with Go x Qiita API x Lambda
I made a slack bot that notifies me of the temperature
I made a C ++ learning site
I made a Line-bot using Python!
I made my own Python library
I made a fortune with Python.
I made a CUI-based translation script
I made a daemon with Python
[Python] I made a bot that tells me the current temperature when I enter a place name on LINE
I get a firewall warning when I start gqlgen's server.go on my Mac
[C language] My locomotive is too slow ~ I made a sl command ~
I made a new AWS S3 bucket
I made a dash docset for Holoviews
I touched "Orator" so I made a note
I made a character counter with Python
Beginner: I made a launcher using dictionary
I made a conversation partner like Siri
I made a Hex map with Python
I made a life game with Numpy
I made a stamp generator with GAN
I made a browser automatic stamping tool.
After studying Python3, I made a Slackbot
I made a roguelike game with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a library for actuarial science
I made a WEB application with Django
I made a neuron simulator with Python
I made a LINE BOT that returns a terrorist image using the Flickr API
A memo that I stumbled upon when doing a quote RT on Twitter Bot
I made a LINE Bot that sends recommended images every day on time
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
I tried to make a translation BOT that works on Discord using googletrans
In Python, I made a LINE Bot that sends pollen information from location information.
A story that I was addicted to when I made SFTP communication with python