릴리스 0.3 파트 1, 더 많은 Discord!
6145 단어 opensource
Discord 봇을 처음 사용하거나 이 게시물을 읽기 시작한 경우 이 봇에 대한 정보와 작동 방식을 확인하는 것이 좋습니다. 다시는 다루지 않을 것입니다.
이번에는 오류 처리와 관련된 문제를 다루었습니다.
findThings는 오류 시 빈 응답을 보냅니다.
#210
AardWolf
에 게시됨
findThings: item_type=mouse&item_id=402 항목 가져오기 오류 - FetchError: 잘못된 json 응답
View on GitHub
따라서 기본적으로 봇이 일부 정보에 대한 요청을 받고 웹사이트가 다운되면 봇은 터미널에 오류를 인쇄하고 Discord 채팅에는 출력물이 없습니다!
그래서 첫 번째 단계는 get 호출을 살펴보는 것이었습니다.
findThing 함수
async function findThing(type, id, options) {
if (!type || !id)
return [];
// If caching is ever implemented it'd be checked here
const qsOptions = new URLSearchParams(options);
qsOptions.append('item_type', type);
qsOptions.append('item_id', id);
const url = 'https://www.agiletravels.com/searchByItem.php?' + qsOptions.toString();
return await fetch(url)
.then((response) => {
if(response.ok){
return response.json();
}
else {
return null;
}
})
.catch(err => {
Logger.log(`findThings: Error getting item ${qsOptions.toString()} - ${err}`);
});
}
이전에는 어떤 문제가 발생했을 때 단순히 오류를 되돌려 보냈습니다. 대신 서버에서 응답이 올바르지 않으면 null을 반환하기로 했습니다. 다음으로 메시지를 만드는 기능을 살펴보겠습니다.
형식마우스 기능
async function formatMice(isDM, mouse, opts) {
const results = await findThing('mouse', mouse.id, opts);
if (results === null) {
const reply = 'Looks like I\'m having a bit of trouble finding your mouse right now.' ;
return reply;
}
const no_stage = ' N/A ';
const target_url = `<https://www.agiletravels.com/attractions.php?mouse=${mouse.id}&timefilter=${opts.timefilter ? opts.timefilter : 'all_time'}>`;
const attracts = results.filter(mouse => mouse.total_hunts > 99)
.map(mice => {
return {
location: mice.location.substring(0, 20),
stage: mice.stage === null ? no_stage : mice.stage.substring(0, 20),
cheese: mice.cheese.substring(0,15),
total_hunts: intToHuman(mice.total_hunts),
ar: mice.rate / 100,
};
});
if (!attracts.length)
return `There were no results with 100 or more hunts for ${mouse.value}, see more at ${target_url}`;
const order = ['location', 'stage', 'cheese', 'ar', 'total_hunts'];
const labels = { location: 'Location', stage: 'Stage', total_hunts: 'Hunts',
ar: '/Hunt', cheese: 'Cheese' };
//Sort the results
attracts.sort((a, b) => parseFloat(b.ar) - parseFloat(a.ar));
attracts.splice(isDM ? 100 : 10);
if (attracts.every(row => row.stage === no_stage))
order.splice(order.indexOf('stage'), 1);
// Column Formatting specification.
/** @type {Object <string, ColumnFormatOptions>} */
const columnFormatting = {};
const headers = order.map(key => {
columnFormatting[key] = {
columnWidth: labels[key].length,
alignRight: !isNaN(parseInt(attracts[0][key], 10)),
};
return { 'key': key, 'label': labels[key] };
});
// Give the numeric column proper formatting.
// TODO: toLocaleString - can it replace integerComma too?
columnFormatting['ar'] = {
alignRight: true,
isFixedWidth: true,
suffix: '%',
columnWidth: 7,
};
let reply = `${mouse.value} (mouse) can be found the following ways:\n\`\`\``;
reply += prettyPrintArrayAsString(attracts, columnFormatting, headers, '=');
reply += '```
\n' + `HTML version at: ${target_url}`;
return reply;
}
조금 길지만 가장 중요한 부분을 살펴보겠습니다.
const results = await findThing('mouse', mouse.id, opts);
if (results === null) {
const reply = 'Looks like I\'m having a bit of trouble finding your mouse right now.' ;
return reply;
}
기본적으로 여기서 우리가 하는 일은 이 함수가 이미 수행하고 있는 findThing 함수를 호출하는 것입니다. 반환 값이 null이면 메시지를 만들고 나머지 유효성 검사 및 분리를 건너뜁니다. 우리의 반응이 틀렸다는 것을 안다면 누가 그것을 필요로 합니까?
검토를 위해 수정 사항을 올려 보겠습니다.
이런! 제출하기 전에 내 코드에서 더 예쁘게 실행한 것으로 밝혀졌고 이제는 사라지고 수많은 항목을 엉망으로 만들었습니다. 패치해서 제대로 제출합시다.
우리는 성공했습니다! 대체로 좋은 일입니다. 솔직히 말해서 이 수정 작업을 하면서 많은 것을 배우지 못했습니다. 나는 프로젝트와 git의 기능에 더 익숙해졌습니다. 하지만 제 성장을 실제로 보여주는 것은 문제를 얼마나 쉽게 받아들이고 수정하고 신속하게 병합할 수 있었는지입니다! 덕분에 정말 개발자로서 발전한 것 같아요.
Reference
이 문제에 관하여(릴리스 0.3 파트 1, 더 많은 Discord!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/fluentinstroll/release-0-3-part-1-more-discord-5g10
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
async function findThing(type, id, options) {
if (!type || !id)
return [];
// If caching is ever implemented it'd be checked here
const qsOptions = new URLSearchParams(options);
qsOptions.append('item_type', type);
qsOptions.append('item_id', id);
const url = 'https://www.agiletravels.com/searchByItem.php?' + qsOptions.toString();
return await fetch(url)
.then((response) => {
if(response.ok){
return response.json();
}
else {
return null;
}
})
.catch(err => {
Logger.log(`findThings: Error getting item ${qsOptions.toString()} - ${err}`);
});
}
async function formatMice(isDM, mouse, opts) {
const results = await findThing('mouse', mouse.id, opts);
if (results === null) {
const reply = 'Looks like I\'m having a bit of trouble finding your mouse right now.' ;
return reply;
}
const no_stage = ' N/A ';
const target_url = `<https://www.agiletravels.com/attractions.php?mouse=${mouse.id}&timefilter=${opts.timefilter ? opts.timefilter : 'all_time'}>`;
const attracts = results.filter(mouse => mouse.total_hunts > 99)
.map(mice => {
return {
location: mice.location.substring(0, 20),
stage: mice.stage === null ? no_stage : mice.stage.substring(0, 20),
cheese: mice.cheese.substring(0,15),
total_hunts: intToHuman(mice.total_hunts),
ar: mice.rate / 100,
};
});
if (!attracts.length)
return `There were no results with 100 or more hunts for ${mouse.value}, see more at ${target_url}`;
const order = ['location', 'stage', 'cheese', 'ar', 'total_hunts'];
const labels = { location: 'Location', stage: 'Stage', total_hunts: 'Hunts',
ar: '/Hunt', cheese: 'Cheese' };
//Sort the results
attracts.sort((a, b) => parseFloat(b.ar) - parseFloat(a.ar));
attracts.splice(isDM ? 100 : 10);
if (attracts.every(row => row.stage === no_stage))
order.splice(order.indexOf('stage'), 1);
// Column Formatting specification.
/** @type {Object <string, ColumnFormatOptions>} */
const columnFormatting = {};
const headers = order.map(key => {
columnFormatting[key] = {
columnWidth: labels[key].length,
alignRight: !isNaN(parseInt(attracts[0][key], 10)),
};
return { 'key': key, 'label': labels[key] };
});
// Give the numeric column proper formatting.
// TODO: toLocaleString - can it replace integerComma too?
columnFormatting['ar'] = {
alignRight: true,
isFixedWidth: true,
suffix: '%',
columnWidth: 7,
};
let reply = `${mouse.value} (mouse) can be found the following ways:\n\`\`\``;
reply += prettyPrintArrayAsString(attracts, columnFormatting, headers, '=');
reply += '```
\n' + `HTML version at: ${target_url}`;
return reply;
}
const results = await findThing('mouse', mouse.id, opts);
if (results === null) {
const reply = 'Looks like I\'m having a bit of trouble finding your mouse right now.' ;
return reply;
}
Reference
이 문제에 관하여(릴리스 0.3 파트 1, 더 많은 Discord!), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/fluentinstroll/release-0-3-part-1-more-discord-5g10텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)