-
Notifications
You must be signed in to change notification settings - Fork 0
/
bots.py
309 lines (237 loc) · 11.8 KB
/
bots.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
309
import discord
import discord.guild
import sched,time
from datetime import datetime,timedelta
from pytimeparse.timeparse import timeparse
import asyncio
from discord.ext import commands
from discord.embeds import EmbedProxy
import validators
TOKEN = ''
#client = discord.Client()
messages = 0
kontrol = bool()
bot = commands.Bot(command_prefix= '$')
@bot.event
async def on_ready():
print(f'Logged in as: {bot.user.name}')
print(f'With ID: {bot.user.id}')
class item():
name = "default" #itemın adı
feature = "" #itemın özellikleri
#price = 0 #müzayede dışında satış fiyatı
Price = None #müzayede başlangıç fiyatı
timer = "" #
def __init__(self,name,feature,Price,timer):
super().__init__()
self.name = name
self.feature = feature
self.Price = Price
self.timer = timer
class muzayede():
mid = 0
item = item("","",None,"")
createdDate = datetime.now()
leftTime = timedelta(0)
currentTime = ""
author = ""
Winner = ""
isFinished = False
def __init__(self,item,createdDate,leftTime,author):
super().__init__()
self.item = item
self.createdDate = createdDate
self.leftTime = leftTime
self.author = author
def creatId(self,mid):
self.mid = mid
async def winner(win):
return win
#%% Delete
@bot.command(pass_context=True)
async def delete(ctx,mid):
channel = ctx.message.channel
try:
msg =await channel.fetch_message(mid)
#print(ctx.message.author.name)
#print(msg.embed[0].fields[4].value)
if msg:
await msg.delete()
else:
fail = await channel.send("Auction not found")
await fail.delete(delay=10)
except Exception as e:
fail = await channel.send("Please, Use command correctly or Auction not found! You can try $helpme")
await fail.delete(delay=10)
#%% Help
#
@bot.command(pass_context=True)
async def helpme(ctx):
channel = ctx.message.channel
try:
user = ctx.message.author
msg = await channel.send(f"""{user.mention} I send help for you <3""")
await msg.delete(delay=10)
embed = discord.Embed( #embed mesajımız oluştu
title = "Help",
description = "",
colour = discord.Colour.blue()
)
embed.add_field(name="Create auction",
value="You can create auction easly! :\n\n $create |ITEM NAME|Item description|Price(only numbers)|Time|Image URL \n",
inline=False)
embed.add_field(name="Offer auction",
value="You can offer auction like this : \n\n $offer AuctionID offer \n Note :You can offer active auction and higger price \n ",
inline=True)
embed.add_field(name="Deleting Auction",
value="You can delete your active auction like this : \n\n $delete AuctionID \n",
inline=True)
embed.add_field(name="Find Auction",
value="You can find active auction on last 30 message like this : \n\n $find \n",
inline=True)
embed.add_field(name="Time",
value="You can define time like this: \n\n 32m,2h32m,3d2h32mü1w3d2h32m,1w 3d 2h 32m,1 w 3 d 2 h 32 m,\n4:13,4:13:02,4:13:02.266,2:04:13:02.266,2 days, \n 4:13:02 (uptime format),2 days, 4:13:02.266,5hr34m56s,\n5 hours, 34 minutes, 56 seconds,5 hrs, 34 mins, 56 secs,2 days, 5 hours, 34 minutes,\n 56 seconds,1.2 m,1.2 min,1.2 mins,1.2 minute,1.2 minutes,172 hours,172 hr,172 h,\n172 hrs,172 hour,1.24 days,5 d,5 day,5 days5.6 wk \n 5.6 week,5.6 weeks",
inline=False)
embed.add_field(name="Note",
value="You can offer ACTIVE auction and You should offer higger price \nYou can find AuctionID inside of active auction messages\nwhen you creating auctions , Please use | between from components and before ITEM NAME , you shouldn't use end.",
inline=False)
#await bot.send_message(user, embed=embed)
embed.set_footer(text='(BETA)Created by MAJIN#4884' )
dm = await user.create_dm()
await dm.send(embed=embed)
except Exception as e:
msg = await channel.send(f"""Some error ^-^ Try $helpme """)
await msg.delete(delay=10)
#%% embed
@bot.command(pass_context=True)
async def create(ctx):
channel = ctx.message.channel #atılan mesaj
try:
taskk = list() #müzayedelirin sıraya alındığı liste
text = ctx.message.content.split('|')
message = ctx.message
if len(text)==5:
newItem = item(text[1],text[2],int(text[3]),(text[4]))
text.append(" ")
elif len(text)>5:
newItem = item(text[1],text[2],int(text[3]),(text[4]))
else:
notEnoughmsg =await channel.send("Please, Use command correctly!\n Did you missing part?\nYou can try $helpme")
await notEnoughmsg.delete(delay=10)
###################
# Burada user yanlış mesaj attığı için mesajı silmek gerekli
# ##################
return
mesDate = ctx.message.created_at
leftTime = timedelta(seconds= timeparse(newItem.timer)) #Str->TimeDelta
nmuzayede = muzayede(newItem,mesDate,leftTime,message.author.name) #yeni bir müzayede oluştur diyorum
embed = discord.Embed( #embed mesajımız oluştu
title = nmuzayede.item.name,
description = nmuzayede.item.feature,
colour = discord.Colour.blue()
)
#user = discord.utils.get(ctx.message.server.members, name = 'MAJIN', discriminator = 4884)
embed.set_footer(text='(BETA)Created by MAJIN#4884' )
valid=validators.url(text[5]) #resim eklenmesi için yzılan url validator modülü ile kontrol ediliyor
if valid:
embed.set_image(url=text[5])
else:
urlFail = await channel.send("Your picture URL is not correct!! So your auction dosen't have picture.")
await urlFail.delete(delay=10)
# Kullanıcı mesajı silinmeli !!!
embed.set_thumbnail(url="") ##############################################
embed.set_author(name=muzayede.author, # Embed mesaja gerekli bilgileri veriyorum
icon_url="") # nmuzayede = yeni muzayede
embed.add_field(name="Price", value=str(nmuzayede.item.Price), inline=True) #
embed.add_field(name="Time Limit", value=nmuzayede.item.timer, inline=True) #
embed.add_field(name="Winner", value=None, inline=True) #
embed.add_field(name="Author",value="{}".format(ctx.message.author.mention),inline=False) #################################################
msg = await channel.send(content=None, embed=embed) #oluşturulan embed mesaj kanala yazdırılıyor
print(msg.id)
nmuzayede.mid=msg.id # Müzayede id si belirleniyor
embed.add_field(name="Id",value=nmuzayede.mid,inline=False) # Id si eklenerek mesaj düzenleniyor
await msg.edit(embed=embed)
taskk.append(asyncio.create_task(count(nmuzayede))) #count asekron metodu içine muzayede sınıfından nesne alarak görev sırasına ekleniyor
for i in taskk: # taskler için döngü
await i #taski çalıştır
msgMuzayede =await channel.fetch_message(nmuzayede.mid)
newMSG = msgMuzayede
await msgMuzayede.delete()
newMSG.embeds[0].color = discord.Colour.red()
newMSG.embeds[0].insert_field_at(4,name="FINISHED",value="See you later....",inline=False)
newMSG.embeds[0].remove_field(5) #id sliniyor
await channel.send(embed=newMSG.embeds[0])
#ne = embed.insert_field_at(2,name="FINISHED",value="The Winner :")
#embed.clear_fields()
#nmuzayede.isFinished=True
#await msg.edit(embed=ne)
except ValueError :
fail = await channel.send("Please, Use command correctly!You can try $helpme")
await fail.delete(delay=10)
except Exception as e:
fail = await channel.send("You make a mistake time or price format,You can try $helpme")
await fail.delete(delay=10)
@bot.command(pass_context=True)
async def offer(ctx,mid,value):
#
# ctx : offer mesajının kendisi
# value : teklif edilen değer
# mid = Müzayede id si mesaja buradan erişiyorum
# Önce offerın bulundu channela gidip
# müzayede idsinden müzayedeye ulaşalım
channel = ctx.message.channel
try:
msgMuzayede =await channel.fetch_message(mid)
#Mesajımıza ulaştık buradan embed ettiğim price kısmını kullanalım
#
fields = msgMuzayede.embeds
embedMsg = fields[0]
currentValue = embedMsg.fields[0].value
if embedMsg.fields[4].name == "FINISHED":
#alert = await channel.send("Its Finished")
#kullanıcın mesajını silme özelliği eklenmeli
m=await channel.send("It is finished!!!")
await m.delete(delay=15)
elif int(value) > int(currentValue):
embedMsg.set_field_at(0,name="Price",value=value,inline=True)
embedMsg.set_field_at(2,name="Winner",value=ctx.message.author.mention,inline=True)
await msgMuzayede.edit(embed=embedMsg)
else:
delete = await channel.send("You should offer higher than {}".format(currentValue))
await delete.delete(delay=20)
#Gerekli izinler alınırsa düşük , gereksiz ve yanlış tekliflerde silinebilinir
#await channel.send(f"""{embedMsg.fields[0].value}""")
#print(type(embedMsg.fields[0]))
#print(type(embedMsg.fields[0].add_fields))
print(type(embedMsg))
except Exception as e:
await channel.send("This Id is unavailable or auction is finished , You can try $helpme")
@bot.command(pass_context=True)
async def find(ctx):
try:
counter = 0
channel = ctx.message.channel
async for msg in channel.history(limit=30):
for embeds in msg.embeds:
if embeds.fields[4]:
#await channel.send(content=f"""{embeds.fields[3].name}""",embed=embeds)
if embeds.fields[4].name != "FINISHED":
await channel.send(embed=embeds)
else:
await channel.send("There is no active trade")
except Exception as e:
if e == "list index out of range":
await channel.send("There is no auction more")
else:
await channel.send(e)
async def count(muzayede):
mesDate = muzayede.createdDate #muzayedenin oluşturulduğu tarih
leftTime = muzayede.leftTime #ne kadar zaman açık kalacağı
fark = datetime.utcnow()- mesDate # şu andan oluşturlma zamanını çıkatıp farkı buluyorum
while(fark<=leftTime): #fark , kalan zamandan küçük oldukça fonksiyon çalışıyor
#print(f'fark {fark}')
suan = datetime.utcnow() # şu an
fark = suan- mesDate # fark
muzayede.currentTime = str(fark) #
await asyncio.sleep(1)
bot.run(TOKEN)