-
Notifications
You must be signed in to change notification settings - Fork 1
/
tword.py
216 lines (172 loc) · 7.71 KB
/
tword.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
#!/usr/bin/python3
import aiohttp
import aiofiles
from urllib.parse import quote_plus
import discord
from bs4 import BeautifulSoup
from discord import Embed
from wiktionaryparser import WiktionaryParser
from tutil import fetch_file, increment_usage, wrap
from constants import DEFAULT_DIR, URL_WOTD, WOLFRAM, URL_WOLF_IMG, URL_WOLF_TXT, URL_KEYWORDS, VERBOSE
from constants import help_dict
parser = WiktionaryParser()
def yandex(message: discord.Message) -> str:
"""
Search Yandex reverse image search
:param message:
:return:
"""
args = message.content.split()
if len(args) < 2:
return 'Please supply a URL to an image.'
yandex = '<https://yandex.com/images/search?url={}&rpt=imageview>'.format(quote_plus(args[1]))
tineye = 'https://tineye.com'
return '{}\n{}'.format(yandex, tineye)
def wiki(message: discord.Message) -> discord.Embed:
"""
Get the www.wiktionary.org entry for a word or phrase
:param message: <Discord.message object>
:return: <str> Banner or None
"""
increment_usage(message.guild, 'dict')
args = message.content.split()
if len(args) == 1 or args[1] == 'help':
banner = Embed(title="Wiktionary Help")
banner.add_field(name='About', value=help_dict['main'])
banner.add_field(name='Aliased Command Names', value=help_dict['alternative'])
return banner
else:
try:
word = message.content.split(' ', maxsplit=1)[1]
result = parser.fetch(word.strip())[0]
etymology = result['etymology']
definitions = result['definitions'][0]
pronunciations = result['pronunciations']
banner = Embed(title="Wiktionary", description=word)
if definitions['partOfSpeech']:
banner.add_field(name="Parts of Speech", value=definitions['partOfSpeech'], inline=False)
if etymology:
banner.add_field(name="Etymology", value=etymology, inline=False)
if definitions['text']:
defs = ''
for each in definitions['text']:
defs += '{} \n'.format(each)
banner.add_field(name="Definitions", value=defs, inline=False)
if definitions['relatedWords']:
defs = ''
for each in definitions['relatedWords']:
for sub in each['words']:
defs += '{}, '.format(sub)
defs += '\n'
banner.add_field(name="Related Words", value=defs, inline=False)
if definitions['examples']:
defs = ''
for each in definitions['examples']:
defs += '{} \n'.format(each)
banner.add_field(name="Examples", value=defs, inline=False)
if pronunciations['text'] or pronunciations['audio']:
defs_text = ''
defs_audio = ''
for each in pronunciations['text']:
defs_text += '{} \n'.format(each)
for each in pronunciations['audio']:
defs_audio += 'https:{} \n'.format(each)
banner.add_field(name="Pronunciation, IPA", value=defs_text, inline=False)
banner.add_field(name="Pronunciation, Audio Sample", value=defs_audio, inline=False)
return banner
except Exception as e:
if VERBOSE >= 0:
print('[!] Exception in wiki: {}'.format(e))
return None
# TODO update help to embed
async def wolfram(message: discord.Message) -> (list, str, discord.Embed):
"""
Return an image based response from the Wolfram Alpha API
:param message: <Discord.message object>
:return: <str> Banner or None
"""
increment_usage(message.guild, 'wolf')
args = message.content.split()
banner = Embed(title="Wolfram Alpha")
try:
if len(args) > 1:
if args[1].lower() in {'simple', 'txt', 'text', 'textual'}:
query_st = quote_plus(' '.join(args[2:]))
query = URL_WOLF_TXT.format(WOLFRAM, query_st)
async with aiohttp.ClientSession() as session:
async with session.get(query) as resp:
if resp.status == 200:
text = await resp.read()
elif resp.status == 501:
return 'Wolfram cannot interpret your request.'
else:
return ['[!] Wolfram Server Status {}'.format(resp.status), None]
text = text.decode('UTF-8')
banner.add_field(name=' '.join(args[2:]), value=text)
return banner
elif args[1].lower() in {'complex', 'graphic', 'graphical', 'image', 'img', 'gif'}:
query_st = quote_plus(' '.join(args[2:]))
query = URL_WOLF_IMG.format(WOLFRAM, query_st)
file_path = '{}/log/wolf/{}.gif'.format(DEFAULT_DIR, message.id)
async with aiohttp.ClientSession() as session:
async with session.get(query) as resp:
if resp.status == 200:
f = await aiofiles.open(file_path, mode='wb')
await f.write(await resp.read())
await f.close()
return [None, file_path]
elif resp.status == 501:
return ['Wolfram cannot interpret your request.', None]
else:
return ['[!] Wolfram Server Status {}'.format(resp.status), None]
banner = Embed(title='Wolfram Help', description=fetch_file('help', 'wolfram'))
return banner
except Exception as e:
if VERBOSE >= 0:
print('[!] Wolfram failed to process command on: {}'.format(message.content))
print('[!] {}'.format(e))
return None
async def get_todays_word(message: discord.Message) -> discord.Embed:
"""
Pull the word of the day from www.wordsmith.org
:param message: <Discord.message object>
:return: <str> Banner
"""
increment_usage(message.guild, 'wotd')
async with aiohttp.ClientSession() as session:
async with session.get(URL_WOTD) as resp:
if resp.status == 200:
text = await resp.read()
else:
if VERBOSE >= 2:
print("[!] Status {}".format(resp.status))
soup = BeautifulSoup(text, "html.parser")
text = soup.get_text()
text = text.split('with Anu Garg')
text = text[1].split('A THOUGHT FOR TODAY')
text = text[0].strip()
text = text.split('\n')
fields = {'header': '', }
for idx, line in enumerate(text):
if line:
if line in URL_KEYWORDS.keys():
fields[line] = ''
key = line
elif idx == 0:
fields['header'] = '{}\n{}'.format(fields['header'], line)
else:
fields[key] = '{}\n{}'.format(fields[key], line)
banner = Embed(title="Word of the Day", description=fields['header'])
fields.pop('header')
for key, val in fields.items():
banner.add_field(name=key, value=val)
banner.set_footer(text=URL_WOTD)
return banner
def get_help(message: discord.Message) -> list:
"""
Return the help file located in ./docs/help
:param message: <Discord.message object>
:return: <String> The local help file
"""
increment_usage(message.guild, 'help')
return wrap(fetch_file('help', 'dict'), 1990)