Skip to content

Instantly share code, notes, and snippets.

@noqisofon
Last active March 15, 2021 11:16
Show Gist options
  • Save noqisofon/c65b41eb7021db54338ff91c46edb875 to your computer and use it in GitHub Desktop.
Save noqisofon/c65b41eb7021db54338ff91c46edb875 to your computer and use it in GitHub Desktop.
( ノ╹◡◡╹)ノ ぶっ子ちゃん
import discord
import json
import tempfile
import os
import os.path
import re
def load_token(filename):
"""
filename を読み込んで json にでこーどして返す。
"""
with open( filename, 'r', encoding='utf-8' ) as out:
return json.load( out )
# くらいあんよつくる
client = discord.Client()
@client.event
async def on_ready():
"""
起動時に呼び出されるよ!
"""
print( 'ログインしたよ!' )
@client.event
async def on_disconnect():
"""
終了時に呼び出されるよ!
"""
print( 'ログアウトしたよ!' )
@client.event
async def on_message(message):
"""
メッセージ受信時に呼び出されるよ!
"""
if message.author.bot:
# bot なので終了
return
if message.content == '/neko':
# /neko ってメッセージを受信したら、「にゃーん」って送信する
await message.channel.send( 'にゃーん' )
if message.content.startswith( '/bukko' ):
content_parts = message.content.split( ' ' )
if len(content_parts) == 1:
# /bukko だけだった場合はこのチャンネルをぶっこぬく
target_channel_name = message.channel.name
else:
# ぶっこぬきたいちゃんぬる名を取り出す
target_channel_name = content_parts[1]
# /bukko ってメッセージを受信したら、指定された名前のチャンネルから URL をぶっこぬく
await message.channel.send( 'はいはい、「{}」チャンネルから URL をぶっこぬいてくればいいのよね? ちょっと待ってなさい'.format( target_channel_name ) )
print( 'チャンネル {} で /bukko されました'.format( message.channel.name ) )
channel_id = -1
# 指定されたチャンネル名を探す
for a_channel in message.guild.text_channels:
if a_channel.name == target_channel_name:
channel_id = a_channel.id
break
if channel_id == -1:
await message.channel.send( 'はあ? {} なんてチャンネル無いんだけど? ふん、知らない!'.format( target_channel_name ) )
return
# URL をためとくやつ
urls = []
# ちゃんぬる ID からチャンネルオブジェクトをゲットする
channel = client.get_channel( channel_id )
async for history_message in channel.history( limit=200 ):
content = history_message.content
if re.match( 'https?://', content ):
# なんか URL っぽかったら回収する
urls.append( content )
print( 'URL が回収できたよ! {} 個見つかったみたい。'.format( len( urls ) ) )
if len( urls ) > 0:
# URL が回収できた場合、一時ファイルに書き込む
fp = tempfile.NamedTemporaryFile( mode='w', newline="\n" )
for url in urls:
print( url, file=fp )
fp.flush()
# 添付するファイルを作成する
attach_file = discord.File( fp.name, '{}.txt'.format( target_channel_name ) )
await message.channel.send( 'ほら、これでいいんでしょ? ふん!', files=[ attach_file ] )
# 送った後、ファイルを閉じる
fp.close()
if os.path.exists( fp.name ):
# 使い終わったのでファイルを削除しておく
os.unlink( fp.name )
else:
# URL が回収できなかった場合、メッセージを送信して終了する
await message.channel.send( 'URL が無かったから、あんたには何もあげられないわ' )
# トークンが記述されたファイルを読み込むよ!
config = load_token( './bukko.json' )
# ぼっとを起動するよ!
client.run( config['token'] )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment