async def inven(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass embed = discord.Embed(title="인벤 주요뉴스", colour=colour) targetSite = 'http://www.inven.co.kr/webzine/news/?hotnews=1' header = { 'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko' } melonrqRetry = rq.get(targetSite, headers=header) melonht = melonrqRetry.text melonsp = bs(melonht, 'html.parser') artists = melonsp.findAll('span', {'class': 'title'}) titles = melonsp.findAll('span', {'class': 'summary'}) for i in range(len(titles)): artist = artists[i].text.strip() title = titles[i].text.strip() embed.add_field(name="{0:3d}".format(i + 1), value='제목:{0} - 내용:{1}'.format(artist, title), inline=False) embed.timestamp = datetime.datetime.utcnow() await ctx.send(embed=embed)
async def queue(self, ctx, page: int = 1): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.queue: return await ctx.send("재생목록에 아무것도 없습니다.") items_per_page = 10 pages = math.ceil(len(player.queue) / items_per_page) start = (page - 1) * items_per_page end = start + items_per_page queue_list = "" for index, track in enumerate(player.queue[start:end], start=start): queue_list += f"`{index + 1}.` [{track.title}]({track.uri})\n" embed = discord.Embed( colour=self.normal_color, description=f"{queue_list}", title=f"{page} / {pages}페이지 - **{len(player.queue)}개의 곡**", ) embed.add_field( name="현재 플레이중인 곡", value=f"[{player.current.title}]({player.current.uri})") embed.set_footer(text=ctx.author.name + " | 태시아 봇#5919", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed)
async def music(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass embed = discord.Embed(title="노래순위", description="노래순위입니다.", colour=colour) targetSite = 'https://www.melon.com/chart/index.htm' header = { 'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko' } melonrqRetry = rq.get(targetSite, headers=header) melonht = melonrqRetry.text melonsp = bs(melonht, 'html.parser') artists = melonsp.findAll('span', {'class': 'checkEllipsis'}) titles = melonsp.findAll('div', {'class': 'ellipsis rank01'}) for i in range(len(titles)): artist = artists[i].text.strip() title = titles[i].text.strip() embed.add_field(name="{0:3d}위".format(i + 1), value='🎶{0} - {1}'.format(artist, title), inline=True) embed.timestamp = datetime.datetime.utcnow() await ctx.send(embed=embed)
async def sc(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass embed = discord.Embed(title="실시간 검색어", description="실시간 검색어입니다.", colour=colour) targetSite = 'https://datalab.naver.com/keyword/realtimeList.naver?groupingLevel=3&where=main' header = { 'User-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko' } source = rq.get(targetSite, headers=header).text soup = BeautifulSoup(source, "html.parser") hotKeys = soup.select("span.item_title") index = 0 for key in hotKeys: index += 1 embed.add_field(name="{}위".format(index), value=key.text, inline=True) embed.timestamp = datetime.datetime.utcnow() await ctx.send(embed=embed)
async def 웹(self, ctx, *, search): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass a = await N.Webkr(query=search) print(a) embed = discord.Embed(title=f'네이버 검색결과!\n{"-----" * 10}') num = 0 for i in a["items"][:3]: title = i["title"] tit = str(title).replace("<b>", "") ti = tit.replace("</b>", "") T = ti.replace(""", "") link = i["link"] des = i["description"] d_e = des.replace("</b>", "") d = d_e.replace("<b>", "") D = d.replace(""", "") DE = D.replace("&", "") num += 1 embed.add_field(name=f"#{str(num)}\n제목", value=str(T), inline=False) embed.add_field(name="미리보기", value=str(DE), inline=False) embed.add_field(name="바로가기", value=f"[자세한 내용 보러가기](<{str(link)}>)", inline=False) embed.set_footer(text=f'검색된 총갯수: {a["total"]}개') await ctx.send(embed=embed)
async def play(self, ctx, *, query: str): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) query = query.strip("<>") if not url_rx.match(query): query = f"ytsearch:{query}" results = await player.node.get_tracks(query) if not results or not results["tracks"]: return await ctx.send("검색 결과가 없습니다!") embed = discord.Embed(color=self.normal_color) if results["loadType"] == "PLAYLIST_LOADED": tracks = results["tracks"] for track in tracks: player.add(requester=ctx.author.id, track=track) embed.title = "플레이리스트 추가 완료!" embed.description = "성공적으로 플레이리스트를 추가했습니다." embed.add_field(name="이름", value=f'{results["playlistInfo"]["name"]}', inline=True) embed.add_field(name="곡 수", value=str(len(tracks)) + "개", inline=True) embed.add_field(name="요청자", value=f"<@!{ctx.author.id}>", inline=True) else: track = results["tracks"][0] embed.title = "트랙 추가 완료!" embed.description = f'```{track["info"]["title"]}```' embed.add_field(name="**URL**", value=f'[클릭]({track["info"]["uri"]})', inline=True) embed.add_field(name="요청자", value=f"<@!{ctx.author.id}>", inline=True) embed.add_field( name="길이", value=f'{lavalink.utils.format_time(track["info"]["length"])}', inline=True, ) embed.set_thumbnail( url= f'https://i.ytimg.com/vi/{track["info"]["identifier"]}/hqdefault.jpg' ) player.add(requester=ctx.author.id, track=track) embed.set_footer(text=ctx.author.name + " | 태시아 봇#5919", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) if not player.is_playing: await player.play()
async def uptime(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass """Tells how long the bot has been running.""" uptime_seconds = round( (datetime.now() - self.start_time).total_seconds()) await ctx.send(f"> 봇이 작동한시간: {util.format_seconds(uptime_seconds)}")
async def volume(self, ctx, volume: int = None): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not volume: return await ctx.send(f"현재 볼륨은 {player.volume}% 입니다.") await player.set_volume(volume) await ctx.message.add_reaction("\U00002705")
async def repeat(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.is_playing: return await ctx.send("재생 중인 것이 없습니다.") player.repeat = not player.repeat await ctx.message.add_reaction("\U00002705")
async def 시간스킵(self, ctx, *, seconds: int): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) track_time = player.position + (seconds * 1000) await player.seek(track_time) await ctx.send( f":hammer_pick: | 시간 스킵: {lavalink.utils.format_time(track_time)}")
async def stop(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.is_playing: return await ctx.send("플레이 중 이지 않습니다.") player.queue.clear() await player.stop() await self.connect_to(ctx.guild.id, None) await ctx.message.add_reaction("\U00002705")
async def remove(self, ctx, index: int): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.queue: return await ctx.send("재생목록에 아무것도 없습니다.") if index > len(player.queue) or index < 1: return await ctx.send(f"인덱스는 1과 {len(player.queue)} 사이 정수여야 합니다.") removed = player.queue.pop(index - 1) # Account for 0-index. await ctx.send(f"`{removed.title}`를 재생목록에서 제거했습니다.")
async def pause(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.is_playing: return await ctx.send("플레이 중이지 않습니다.") if player.paused: await player.set_pause(False) await ctx.message.add_reaction("\U00002705") else: await player.set_pause(True) await ctx.message.add_reaction("\U00002705")
async def botinfo(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass if (self.app.latency * 1000) > 210: embed = discord.Embed(title="봇정보", color=0xff0000, timestamp=datetime.datetime.now()) embed.add_field(name="이름", value="태시아", inline=True) embed.add_field(name="핑", value=""" 현재 핑: {0}ms 상태: 불안정⛔""".format( round(self.app.latency * 1000))) embed.add_field(name="접속한 서버수", value=f"{len(self.app.guilds)}개의 서버에 접속함", inline=False) embed.add_field(name="접속한 서버들의 멤버수", value=f"{len(self.app.users)}명의 멤버", inline=True) embed.set_footer(text=f"태시아봇 | 2.0", icon_url="https://i.imgur.com/TRxVv4X.png") embed.set_thumbnail(url="https://i.imgur.com/TRxVv4X.png") await ctx.send(embed=embed) else: embed = discord.Embed(title="봇정보", color=0xff0000, timestamp=datetime.datetime.now()) embed.add_field(name="이름", value="태시아", inline=True) embed.add_field(name="핑", value=""" 현재 핑: {0}ms 상태: 양호✅""".format( round(self.app.latency * 1000))) embed.add_field(name="접속한 서버수", value=f"{len(self.app.guilds)}개의 서버에 접속함", inline=False) embed.add_field(name="접속한 서버들의 멤버수", value=f"{len(self.app.users)}명의 멤버", inline=True) embed.set_footer(text=f"태시아봇 | 2.0", icon_url="https://i.imgur.com/TRxVv4X.png") embed.set_thumbnail(url="https://i.imgur.com/TRxVv4X.png") await ctx.send(embed=embed)
async def 단축(self, ctx, *, orgurl): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass encText = urllib.parse.quote(orgurl) data = "url=" + encText url = "https://openapi.naver.com/v1/util/shorturl" request = urllib.request.Request(url) request.add_header("X-Naver-Client-Id", client_id) request.add_header("X-Naver-Client-Secret", client_secret) response = urllib.request.urlopen(request, data=data.encode("utf-8")) rescode = response.getcode() if (rescode == 200): response_body = response.read() print(response_body.decode('utf-8')) sid = response_body.decode('utf-8') answer = json.loads(sid) a = answer["result"] embed = discord.Embed(title="단축성공! ✅") if len(orgurl) > 100: call_url = f'{orgurl[:100]}...' else: call_url = orgurl embed.add_field(name=f"요청한 원본링크: {call_url}", value="** **", inline=False) embed.add_field(name=f"단축된 링크: {a['url']}", value="\n** **", inline=False) embed.add_field(name="단축된 링크QR이미지", value="** **", inline=False) embed.set_image(url=f"{a['url']}.qr") await ctx.send(embed=embed) else: print("Error Code:" + rescode) embed = discord.Embed(title=f"ERROR..단축실패 ❌\n에러코드: {rescode}") if len(orgurl) > 100: call_url = f'{orgurl[:100]}...' else: call_url = orgurl embed.add_field(name=f"요청한 원본링크: {call_url}", value="** **", inline=False) await ctx.send(embed=embed)
async def disconnect(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.is_connected: return await ctx.send("연결되지 않았습니다.") if not ctx.author.voice or ( player.is_connected and ctx.author.voice.channel.id != int(player.channel_id)): return await ctx.send("저랑 같은 채널에 들어와주세요!") player.queue.clear() await player.stop() await self.connect_to(ctx.guild.id, None) await ctx.message.add_reaction("👋")
async def dev(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass embed = discord.Embed(title="크레딧", color=0x00ff56) embed.add_field( name="개발자", value= "가위#1111\n트위터:```https://twitter.com/tfam_is_love```\n유튜브:```https://bit.ly/2Z0550F```" ) embed.add_field(name="베타테스터", value="공식서버에 계신 모든분들.", inline=False) embed.add_field(name="후원", value="테일러(서버운영비용)", inline=False) embed.add_field( name="참고한 오픈소스", value= "[깃허브1](<https://github.com/hands8142/discord-bot>)\n[깃허브2](<https://github.com/SAHYUN/Pulse-Group_Moderation-Bot>)\n[깃허브3](<https://github.com/Puilin/Puilin-Bot>)\n[깃허브4](<https://github.com/minibox24/MiniBOT>)", inline=False) embed.set_footer(text="도움을 주신분들 모두 감사합니다😁") await ctx.send(embed=embed)
async def 뉴스(self, ctx, *, search): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass a = await N.News(query=search) print(a) embed = discord.Embed(title='뉴스 검색결과!') num = 0 for i in a["items"][:3]: title = i["title"] tit = str(title).replace("<b>", "") ti = tit.replace("</b>", "") T = ti.replace(""", "") link = i["originallink"] des = i["description"] d_e = des.replace("</b>", "") d = d_e.replace("<b>", "") D = d.replace(""", "") DE = D.replace("&", "") num += 1 '''b = str(a["total"]) c = b[:1] d = b[2:5] e = b[6:9]''' embed.add_field(name=f"#{str(num)}", value=f'기사제목- {str(T)}', inline=False) embed.add_field(name="미리보기", value=str(DE), inline=False) embed.add_field(name="게시일", value=i["pubDate"][:-6]) embed.add_field( name="** **", value=f"[자세한 내용 보러가기](<{str(link)}>)\n{'-----' * 10}", inline=False) embed.set_footer(text=f'검색된 뉴스 기사 총갯수: {a["total"]}개') await ctx.send(embed=embed)
async def 한강(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass url = "https://api.winsub.kr/hangang/?key=$2y$10$hb02LEbU05.z0Eq8gQDjyuvVsI1xgdBhB9RP8WdjcYgsXizyDZE9i" request = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) response = urllib.request.urlopen(request) response_body = response.read() sid = response_body.decode('utf-8') answer = json.loads(sid) a = answer["temp"] b = answer["time"] c = answer["notify"] d = answer["quote"] embed = discord.Embed(colour=discord.colour.Colour.blue()) embed.add_field(name=f'현재온도: {a}', value=f'온도측정한시간: {b}', inline=False) embed.add_field(name='살아가는데있어 도움이 되는글', value=f'{d}', inline=False) embed.add_field(name='안내글', value=f'{c}', inline=False) await ctx.send(embed=embed)
async def now(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass player = self.bot.lavalink.player_manager.get(ctx.guild.id) if not player.current: return await ctx.send("재생 중인 것이 없습니다.") position = lavalink.utils.format_time(player.position) if player.current.stream: duration = "라이브 (실시간)" else: duration = lavalink.utils.format_time(player.current.duration) song = f"**[{player.current.title}]()**\n()" embed = discord.Embed( color=self.normal_color, title="현재 플레이 중", description=f"```{player.current.title}```", ) embed.add_field(name="URL", value=f"[클릭]({player.current.uri})", inline=True) embed.add_field(name="요청자", value=f"<@!{player.current.requester}>", inline=True) embed.add_field(name="길이", value=f"{position} / {duration}", inline=True) embed.set_thumbnail( url= f"https://i.ytimg.com/vi/{player.current.identifier}/hqdefault.jpg" ) embed.set_footer(text=ctx.author.name + " | 태시아 봇#5919", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed)
async def 한강이미지(self, ctx): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass url = "https://api.winsub.kr/hangang/?key=$2y$10$hb02LEbU05.z0Eq8gQDjyuvVsI1xgdBhB9RP8WdjcYgsXizyDZE9i" request = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) response = urllib.request.urlopen(request) response_body = response.read() sid = response_body.decode('utf-8') answer = json.loads(sid) print(answer) a = answer["temp"] b = answer["time"] c = answer["notify"] d = answer["quote"] D = d.replace("\n", "") print(d) img = Image.open( "한강석양.png") # Replace infoimgimg.png with your background image. draw = ImageDraw.Draw(img) font = ImageFont.truetype( "etc.otf", 30) # Make sure you insert a valid font from your folder. fontbig = ImageFont.truetype( "temp.otf", 100) # Make sure you insert a valid font from your folder. # (x,y)::↓ ↓ ↓ (text)::↓ ↓ (r,g,b)::↓ ↓ ↓ draw.text((275, 200), f'{a}', (255, 255, 255), font=fontbig) # draws Information draw.text((95, 435), f'"{D}"', (255, 255, 255), font=font) # draws the Username of the user img.save('한강석양_result.png') # Change infoimg2.png if needed. await ctx.send(file=discord.File('한강석양_result.png'))
async def quickpoll(self, ctx, question, time: str, *options: str): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass ser = str(ctx.author.id) cur.execute(f"SELECT * FROM license WHERE user= {ser}") L_i = cur.fetchone() print(ser) if L_i == None: sv = discord.Embed(title="⛔명령어 거부됨", colour=discord.colour.Colour.dark_purple()) sv.add_field( name= "이런..서비스에 가입하지 않으셨네요..가입을 원하시면 아래반응에 응답해주세요.\n\n가입할시 **__정보제공(서버ID,유저ID,유저닉네임)__**에 동의하시는것으로 간주됩니다.", value="** **", inline=False) msg = await ctx.send(embed=sv) reaction_list = ['✅', '❎'] for r in reaction_list: await msg.add_reaction(r) def check(reaction, user): return user == ctx.author and str( reaction ) in reaction_list and reaction.message.id == msg.id try: reaction, user = await self.bot.wait_for('reaction_add', timeout=60, check=check) if str(reaction) == "✅": tm = datetime.datetime.utcnow() cur.execute("INSERT INTO license VALUES (?, ?)", (ser, tm)) conn.commit() return await ctx.send( "✅가입되었습니다.\n탈퇴를 원하신다면 'ㅌ전체탈퇴'를 명령해주세요.") elif str(reaction) == "❎": conn.commit() return await ctx.send("❌가입을 거부하셨습니다.") except asyncio.TimeoutError: conn.commit() return await ctx.send("시간초과로 가입이 취소되었습니다.") else: if len(options) <= 1: await ctx.send('2개이상의 선택지를 만들어주세요!') return if len(options) > 10: await ctx.send('선택지는 최대10개까지에요! 10개 이하로 낮추어주세요.') return if len(options ) == 2 and options[0] == 'yes' and options[1] == 'no': reactions = ['✅', '❌'] else: reactions = [ '1⃣', '2⃣', '3⃣', '4⃣', '5⃣', '6⃣', '7⃣', '8⃣', '9⃣', '🔟' ] description = [] for x, option in enumerate(options): description += '\n {} {}'.format(reactions[x], option) embed = discord.Embed(title="**투표주제:** " + "**" + question + "**", description=''.join(description), color=discord.Colour(0xFF355E)) react_message = await ctx.send(embed=embed) for reaction in reactions[:len(options)]: await react_message.add_reaction(reaction) print(react_message.id) Day = 0 Hour = 0 Minute = 0 Second = 0 a = [time] if time.find("d") != -1: a = a[0].split("d") day = a.pop(0).strip() Day = int(day) if time.find("h") != -1: a = a[0].split("h") hour = a.pop(0).strip() Hour = int(hour) if time.find("m") != -1: a = a[0].split("m") minute = a.pop(0).strip() Minute = int(minute) if time.find("s") != -1: a = a[0].split("s") second = a.pop(0).strip() Second = int(second) embed.add_field(name='투표종료까지:', value="로딩..") react_message.edit(embed=embed) while True: embed.remove_field(index=0) embed.add_field( name='투표종료까지:', value= f"{str(Day)}일 {str(Hour)}시간 {str(Minute)}분 {str(Second)}초 남았습니다." ) await react_message.edit(embed=embed) if Second <= 0 and Minute > 0: Minute -= 1 Second = 60 if Minute <= 0 and Hour > 0: Hour -= 1 Minute = 59 if Hour <= 0 and Day > 0: Day -= 1 Hour = 23 await asyncio.sleep(5) if Second > 0: Second -= 5 if Day == 0 and Hour == 0 and Minute == 0 and Second == 0: embed.remove_field(index=0) embed.add_field(name='투표종료까지:', value="투표마감") await react_message.edit(embed=embed) id = react_message.id poll_message = await ctx.message.channel.fetch_message(id) if not poll_message.embeds: return embed = poll_message.embeds[0] if poll_message.author != self.bot.user: return unformatted_options = [ x.strip() for x in embed.description.split('\n') ] opt_dict = {x[:2]: x[3:] for x in unformatted_options} if unformatted_options[0][0] == '1' \ else {x[:1]: x[2:] for x in unformatted_options} # check if we're using numbers for the poll, or x/checkmark, parse accordingly voters = [ self.bot.user.id ] # add the bot's ID to the list of voters to exclude it's votes tally = {x: 0 for x in opt_dict.keys()} for reaction in poll_message.reactions: if reaction.emoji in opt_dict.keys(): reactors = await reaction.users().flatten() for reactor in reactors: if reactor.id not in voters: tally[reaction.emoji] += 1 voters.append(reactor.id) output = discord.Embed(title='투표결과! \n\n{}\n'.format(embed.title) + \ '\n'.join( ['{}: {}표'.format(opt_dict[key], tally[key]) for key in tally.keys()]), color=discord.Colour(0xFF355E)) await ctx.send(ctx.author.mention, embed=output) embed = discord.Embed(title="투표주제:\n만료된 투표입니다.") await react_message.edit(embed=embed) break
async def info(self, ctx, user: discord.Member = None): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass if user is None: user = ctx.author img = Image.open( "infoimgimg.png" ) # Replace infoimgimg.png with your background image. draw = ImageDraw.Draw(img) font = ImageFont.truetype( "1.ttf", 55) # Make sure you insert a valid font from your folder. fontbig = ImageFont.truetype( "2.TTF", 100) # Make sure you insert a valid font from your folder. # (x,y)::↓ ↓ ↓ (text)::↓ ↓ (r,g,b)::↓ ↓ ↓ draw.text((370, 25), "유저정보 카드", (255, 255, 255), font=fontbig) # draws Information draw.text((50, 150), "유저이름: {}".format(user.name), (255, 255, 255), font=font) # draws the Username of the user draw.text((50, 220), "ID: {}".format(user.id), (255, 255, 255), font=font) # draws the user ID draw.text((50, 290), "유저상태:{}".format(user.status), (255, 255, 255), font=font) # draws the user status draw.text((50, 360), "디코가입일: {}".format(user.created_at), (255, 255, 255), font=font) # When the account was created draw.text((50, 430), "서버별명:{}".format(user.display_name), (255, 255, 255), font=font) # Nickname of the user draw.text((50, 500), "최고역할:{}".format(user.top_role), (255, 255, 255), font=font) # draws the top rome draw.text((50, 570), "서버가입일:{}".format(user.joined_at), (255, 255, 255), font=font) # draws info about when the user joined img.save('infoimg2.png') # Change infoimg2.png if needed. await ctx.send(file=discord.File('infoimg2.png')) else: img = Image.open( "infoimgimg.png" ) # Replace infoimgimg.png with your background image. draw = ImageDraw.Draw(img) font = ImageFont.truetype( "1.ttf", 55) # Make sure you insert a valid font from your folder. fontbig = ImageFont.truetype( "2.TTF", 100) # Make sure you insert a valid font from your folder. # (x,y)::↓ ↓ ↓ (text)::↓ ↓ (r,g,b)::↓ ↓ ↓ draw.text((370, 25), "유저정보 카드", (255, 255, 255), font=fontbig) # draws Information draw.text((50, 150), "유저이름: {}".format(user.name), (255, 255, 255), font=font) # draws the Username of the user draw.text((50, 220), "ID: {}".format(user.id), (255, 255, 255), font=font) # draws the user ID draw.text((50, 290), "유저상태:{}".format(user.status), (255, 255, 255), font=font) # draws the user status draw.text((50, 360), "디코가입일: {}".format(user.created_at), (255, 255, 255), font=font) # When the account was created draw.text((50, 430), "서버별명:{}".format(user.display_name), (255, 255, 255), font=font) # Nickname of the user draw.text((50, 500), "최고역할:{}".format(user.top_role), (255, 255, 255), font=font) # draws the top rome draw.text((50, 570), "서버가입일:{}".format(user.joined_at), (255, 255, 255), font=font) # draws info about when the user joined img.save('infoimg2.png') # Change infoimg2.png if needed. await ctx.send(file=discord.File('infoimg2.png'))
async def my_rank(self, ctx, member: discord.Member = None): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass if member == None: member = ctx.author level_cur.execute( f"SELECT * FROM level WHERE user= {member.id} AND guild_id = {ctx.guild.id}" ) L_V = level_cur.fetchone() path = r"C:\Users\Administrator\Desktop\teasia2.0\LV.png" with requests.get(member.avatar_url) as r: img_data = r.content with open('profile.jpg', 'wb') as handler: handler.write(img_data) if L_V is not None: im1 = Image.open("background.png") im2 = Image.open("profile.jpg") draw = ImageDraw.Draw(im1) font = ImageFont.truetype("2.TTF", 28) font1 = ImageFont.truetype("1.TTF", 28) draw.text((145, 15), f"{member.display_name}", (255, 255, 255), font=font) draw.text((160, 50), str(L_V[2]) + ".Lv", (255, 255, 255), font=font1) draw.text((160, 80), str(L_V[1]) + ".exp", (255, 255, 255), font=font1) size = 129 im2 = im2.resize((size, size), resample=0) mask_im = Image.new("L", im2.size, 0) draw = ImageDraw.Draw(mask_im) draw.ellipse((0, 0, size, size), fill=255) mask_im.save('mask_circle.png', quality=100) back_im = im1.copy() back_im.paste(im2, (11, 11), mask_im) back_im.save('LV.png', quality=100) f = discord.File(path, filename="LV.png") await ctx.send(file=f) conn.commit() else: await ctx.send('이런..당신의 레벨정보가 존재하지않아요!') conn.commit() conn.commit() else: cur.execute( f"SELECT * FROM level WHERE user= {member.id} AND guild_id = {ctx.guild.id}" ) L_V = cur.fetchone() path = r"C:\Users\Administrator\Desktop\teasia2.0\LV.png" with requests.get(member.avatar_url) as r: img_data = r.content with open('profile.jpg', 'wb') as handler: handler.write(img_data) if L_V is not None: im1 = Image.open("background.png") im2 = Image.open("profile.jpg") draw = ImageDraw.Draw(im1) font = ImageFont.truetype("2.TTF", 28) font1 = ImageFont.truetype("1.TTF", 28) draw.text((145, 15), f"{member.display_name}", (255, 255, 255), font=font) draw.text((160, 50), str(L_V[2]) + ".Lv", (255, 255, 255), font=font1) draw.text((160, 80), str(L_V[1]) + ".exp", (255, 255, 255), font=font1) size = 129 im2 = im2.resize((size, size), resample=0) mask_im = Image.new("L", im2.size, 0) draw = ImageDraw.Draw(mask_im) draw.ellipse((0, 0, size, size), fill=255) mask_im.save('mask_circle.png', quality=100) back_im = im1.copy() back_im.paste(im2, (11, 11), mask_im) back_im.save('LV.png', quality=100) f = discord.File(path, filename="LV.png") await ctx.send(file=f) conn.commit() else: await ctx.send('이런..지정한 상대의 레벨정보가 존재하지않아요!') conn.commit() conn.commit()
async def weather(self, ctx, location): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass embed = discord.Embed(title="날씨", colour=colour) Finallocation = location + '날씨' LocationInfo = "" NowTemp = "" CheckDust = [] url = 'https://search.naver.com/search.naver?where=nexearch&sm=top_hty&fbm=1&ie=utf8&query=' + Finallocation hdr = { 'User-Agent': ('mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/78.0.3904.70 safari/537.36' ) } req = requests.get(url, headers=hdr) html = req.text soup = BeautifulSoup(html, 'html.parser') bsObj = bs4.BeautifulSoup(html, "html.parser") # 오류 체크 ErrorCheck = soup.find('span', {'class': 'btn_select'}) if 'None' in str(ErrorCheck): await ctx.send('검색 오류발생') else: # 지역 정보 for i in soup.select('span[class=btn_select]'): LocationInfo = i.text NowTemp = soup.find('span', { 'class': 'todaytemp' }).text + soup.find('span', { 'class': 'tempmark' }).text[2:] WeatherCast = soup.find('p', {'class': 'cast_txt'}).text TodayMorningTemp = soup.find('span', {'class': 'min'}).text TodayAfternoonTemp = soup.find('span', {'class': 'max'}).text TodayFeelTemp = soup.find('span', {'class': 'sensible'}).text[5:] TodayUV = soup.find('span', { 'class': 'indicator' }).text[4:-2] + " " + soup.find('span', { 'class': 'indicator' }).text[-2:] CheckDust1 = soup.find('div', {'class': 'sub_info'}) CheckDust2 = CheckDust1.find('div', {'class': 'detail_box'}) for i in CheckDust2.select('dd'): CheckDust.append(i.text) FineDust = CheckDust[0][:-2] + " " + CheckDust[0][-2:] UltraFineDust = CheckDust[1][:-2] + " " + CheckDust[1][-2:] Ozon = CheckDust[2][:-2] + " " + CheckDust[2][-2:] tomorrowAreaBase = bsObj.find('div', {'class': 'tomorrow_area'}) tomorrowMoring1 = tomorrowAreaBase.find( 'div', {'class': 'main_info morning_box'}) tomorrowMoring2 = tomorrowMoring1.find('span', {'class': 'todaytemp'}) tomorrowMoring = tomorrowMoring2.text.strip() # 내일 오전 온도 print(tomorrowMoring) tomorrowValue1 = tomorrowMoring1.find('div', {'class': 'info_data'}) tomorrowValue = tomorrowValue1.text.strip() # 내일 오전 날씨상태, 미세먼지 상태 print(tomorrowValue) tomorrowAreaBase = bsObj.find('div', {'class': 'tomorrow_area'}) tomorrowAllFind = tomorrowAreaBase.find_all( 'div', {'class': 'main_info morning_box'}) tomorrowAfter1 = tomorrowAllFind[1] tomorrowAfter2 = tomorrowAfter1.find('p', {'class': 'info_temperature'}) tomorrowAfter3 = tomorrowAfter2.find('span', {'class': 'todaytemp'}) tomorrowAfterTemp = tomorrowAfter3.text.strip() # 내일 오후 온도 print(tomorrowAfterTemp) tomorrowAfterValue1 = tomorrowAfter1.find('div', {'class': 'info_data'}) tomorrowAfterValue = tomorrowAfterValue1.text.strip() print(tomorrowAfterValue) # 내일 오후 날씨상태,미세먼지 embed.add_field(name="|🗺️지역", value=f"{LocationInfo}") embed.add_field(name="|🌡️현재온도", value=f"|{NowTemp}", inline=True) embed.add_field(name="|🧍🏻체감온도", value=f"|{TodayFeelTemp}", inline=True) embed.add_field(name="|ℹ️현재날씨", value=f"{WeatherCast}", inline=True) embed.add_field(name="|☀️자외선", value=f"|{TodayUV}", inline=True) embed.add_field(name="|🌡️최저온도/최고온도", value=f"|{TodayMorningTemp}/{TodayAfternoonTemp}", inline=True) embed.add_field(name="|🌫️미세먼지", value=f"{FineDust}", inline=True) embed.add_field(name="|🌫️초미세먼지", value=f"|{UltraFineDust}", inline=True) embed.add_field(name="|☀오존 지수", value=f"|{Ozon}", inline=True) embed.add_field(name='|🌡내일 오전/오후온도', value='|' + tomorrowMoring + '˚/' + tomorrowAfterTemp + '˚', inline=True) # 내일오전날씨 embed.add_field(name='|☀내일 오전날씨상태', value='|' + tomorrowValue, inline=True) # 내일오전 날씨상태 embed.add_field(name='|☀내일 오후날씨상태', value='|' + tomorrowAfterValue, inline=True) # 내일오후 날씨상태 embed.timestamp = datetime.datetime.utcnow() await ctx.send(embed=embed)
async def 영화(self, ctx, *, query): ch = Checker(ctx=ctx) em = Embed(ctx=ctx) if await ch.licence() == 400: return await ctx.send(embed=em.no_()) elif await ch.licence() == 200: pass global emoji_star, ST_AR1, AC a = await N.Movie(query=query) print(a) embed = discord.Embed(colour=discord.Colour.blue()) num = 0 for i in a["items"][:3]: director = i["director"] direct = str(director).replace("|", "\n") actor = i["actor"] act = str(actor).replace("|", "\n") if i["subtitle"] == '': sub = 'ERROR! (정보없음)' else: sub = i["subtitle"] title = i["title"] tit = title.replace("<b>", "") ti = tit.replace("</b>", "") embed.add_field(name=f'#{str(num)}\n제목: **{ti}({sub})**', value='** **', inline=False) embed.add_field(name="개봉일", value=i["pubDate"]) if act == '': ac = 'ERROR! (정보없음)' else: ac = act if len(ac) > 15: AC = f'{ac[:15]}...' dire = f'{ac[:10]}...' num += 1 star = i["userRating"] STAR1 = star[:1] STAR2 = star[2:3] if int(STAR2) >= 5: ST_AR1 = int(STAR1) + 1 print(ST_AR1) elif int(STAR2) <= 4: ST_AR1 = int(STAR1) + 0 print(ST_AR1) if ST_AR1 == 0: emoji_star = '☆☆☆☆☆' print('0') elif ST_AR1 == 1 or ST_AR1 == 2: emoji_star = '★☆☆☆☆' print('1') elif ST_AR1 == 3 or ST_AR1 == 4: emoji_star = '★★☆☆☆' print('2') elif ST_AR1 == 5 or ST_AR1 == 6: emoji_star = '★★★☆☆' print('3') elif ST_AR1 == 7 or ST_AR1 == 8: emoji_star = '★★★★☆' print('4') elif ST_AR1 == 9 or ST_AR1 == 10: emoji_star = '★★★★★' print('5') print(STAR1) embed.add_field( name="평점", value=f'{STAR1}.{STAR2}점, 별점: {emoji_star}({ST_AR1}점)') embed.add_field(name="감독", value=dire, inline=False) embed.add_field(name="배우", value=AC, inline=False) embed.add_field( name="바로가기", value= f"[자세한 내용 보러가기]({i['link']})\n[포스터보러가기]({i['image']})\n{'-----' * 10}" ) embed.set_footer(text='별점은 소숫점1의 자리에서 반올림한 값으로 계산합니다.') print(i["userRating"]) await ctx.send(embed=embed)